Java | PTA:试试多线程

导读:本篇文章讲解 Java | PTA:试试多线程,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

编写4个线程,第一个线程从1加到25,第二个线程从26加到50,第三个线程从51加到75,第四个线程从76加到100,最后再把四个线程计算的结果相加。

输入格式:

输出格式:

最终结果

输入样例:

输出样例:

5050

import java.util.Scanner;

class CountThread implements Runnable{
	private int n;
	private int summ=0;
	private boolean f=false;
	public CountThread() {
		
	}
	public CountThread(int n) {
		this.n = n;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		int t=25;
		while (t>0) {
			summ+=n;
			this.n++;
			t--;
		}
		this.f=true;
	}
	public int getN() {
		return n;
	}

	public void setN(int n) {
		this.n = n;
	}
	public boolean isF() {
		return f;
	}
	public void setF(boolean f) {
		this.f = f;
	}
	public int getSumm() {
		return summ;
	}
	public void setSumm(int summ) {
		this.summ = summ;
	}
	
}

public class Main {
	public static void main(String[] args) {
		CountThread []countThread = new CountThread[4];
		for (int i=1;i<100;i+=25) {
			int index = (int) Math.floor(i/25);
			countThread[index]=new CountThread(i);
		}
		for(int i=0;i<4;i++) {
			new Thread(countThread[i]).start();
		}
		while(!countThread[0].isF()||!countThread[1].isF()||!countThread[2].isF()||!countThread[3].isF()) {}
		System.out.println(countThread[0].getSumm()+countThread[1].getSumm()+countThread[2].getSumm()+countThread[3].getSumm());
	}
}

另外一种更高明的方法:(用了thread.join()方法)

import java.util.Scanner;


class CountThread implements Runnable{
	private int n;
	private int summ=0;
	private boolean f=false;
	public CountThread() {
		
	}
	public CountThread(int n) {
		this.n = n;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		int t=25;
		while (t>0) {
			summ+=n;
			this.n++;
			t--;
		}
		this.f=true;
	}
	public int getN() {
		return n;
	}

	public void setN(int n) {
		this.n = n;
	}
	public boolean isF() {
		return f;
	}
	public void setF(boolean f) {
		this.f = f;
	}
	public int getSumm() {
		return summ;
	}
	public void setSumm(int summ) {
		this.summ = summ;
	}
	
}

public class Main {
	public static void main(String[] args) {
		CountThread []countThread = new CountThread[4];
		Thread [] threads = new Thread[4];
		for (int i=1;i<100;i+=25) {
			int index = (int) Math.floor(i/25);
			countThread[index]=new CountThread(i);
		}
		for(int i=0;i<4;i++) {
			threads[i] = new Thread(countThread[i]);
			threads[i].start();
		}
		for(int i=0;i<4;i++) {
			try {
				threads[i].join();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		int summ=0;
		for(int i=0;i<4;i++) {
			summ+=countThread[i].getSumm();
		}
		System.out.println(summ);
	}
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/103106.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!