多线程作加法问题

题目:编写10个线程,第1个线程从1加到10,第二个线程从11加到20……第十个线程从91加到100,最后再,10个线程结果相加。

思路:依次调用thread.join(),主线程输出结果。注意:sum为共享变量,访问共享变量时,用synchronized同步

 

package test1101;

public class test04 {

	public static int sum=0;
	public static Object LOCK=new Object();
	
	class Threadtest extends Thread{

		private int begin;
		private int end;
		@Override
		public void run() {
			synchronized (LOCK) {
				for(int i=begin;i<=end;i++){
					sum+=i;
				}
				System.out.println(Thread.currentThread().getName()+"的和:"+sum);
			}
		}
		public Threadtest(int begin, int end) {
			this.begin = begin;
			this.end = end;
		}	
	}
	public static void main(String[] args)throws InterruptedException {
		test04 t11=new test04();
		Threadtest t1=t11.new Threadtest(1, 10);
		t1.setName("1到10");
		Threadtest t2=t11.new Threadtest(11, 20);
		t2.setName("11到20");
		Threadtest t3=t11.new Threadtest(21, 30);
		t3.setName("21到30");
		Threadtest t4=t11.new Threadtest(31, 40);
		t4.setName("31到40");
		Threadtest t5=t11.new Threadtest(41, 50);
		t5.setName("41到50");
		Threadtest t6=t11.new Threadtest(51, 60);
		t6.setName("51到60");
		Threadtest t7=t11.new Threadtest(61, 70);
		t7.setName("61到70");
		Threadtest t8=t11.new Threadtest(71, 80);
		t8.setName("71到80");
		Threadtest t9=t11.new Threadtest(81, 90);
		t9.setName("81到90");
		Threadtest t10=t11.new Threadtest(91, 100);
		t10.setName("91到100");
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		t5.start();
		t6.start();
		t7.start();
		t8.start();
		t9.start();
		t10.start();
		t1.join();
		t2.join();
		t3.join();
		t4.join();
		t5.join();
		t6.join();
		t7.join();
		t8.join();
		t9.join();
		t10.join();
		System.out.println("总和:"+sum);			
	}
}

运行结果:

1到10的和:55
61到70的和:710
71到80的和:1465
81到90的和:2320
31到40的和:2675
21到30的和:2930
41到50的和:3385
11到20的和:3540
51到60的和:4095
91到100的和:5050
总和:5050

 

你可能感兴趣的:(面试题)