11、编写10个线程,第一个线程从1加到10,第二个线程从11加到20…第十个线程从91加到100,最后再把十个线程结果相加。
public class Accumulator extends Thread {
private int stratNum;
public static int sum;
public Accumulator(int startNum) {
this.stratNum = startNum;
}
public static synchronized void add(int num) {
sum += num;
}
public void run() {
int sum = 0;
for (int i = 0; i < 10; i++) {
sum += stratNum + i;
}
add(sum);
}
public static void main(String[] args) throws Exception {
Thread[] threadList = new Thread[10];
for (int i = 0; i < 10; i++) {
threadList[i] = new Accumulator(10 * i + 1);
threadList[i].start();
}
for (int i = 0; i < 10; i++) {
threadList[i].join();
}
System.out.println("Sum is : " + sum);
}
}
版权声明:本文为xiaoye142034原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。