【题意】:开6条线程计算累加1 -> 10000000
【思路】:生产者-消费者 经典模型
多个生产者负责生产(累加)作业
生产者将生产结果存入共享仓库中
消费者(主线程)从共享仓库中取出结果
/**
* 多线程计算累加数
*/
public class Accumulate {
public static void main(String[] args) {
Storage storage = new Storage();
// 为多个计算器对象创建线程
Thread calThread1 = new Thread(new Calculate(1, storage), "Thread-1");
Thread calThread2 = new Thread(new Calculate(2, storage), "Thread-2");
Thread calThread3 = new Thread(new Calculate(3, storage), "Thread-3");
Thread calThread4 = new Thread(new Calculate(4, storage), "Thread-4");
Thread calThread5 = new Thread(new Calculate(5, storage), "Thread-5");
Thread calThread6 = new Thread(new Calculate(6, storage), "Thread-6");
calThread1.start();
calThread2.start();
calThread3.start();
calThread4.start();
calThread5.start();
calThread6.start();
// 打印最终结果
storage.printTotal();
}
}
/**
* 计算器对象,负责计算start -> end
*/
class Calculate implements Runnable {
private Storage storage;
private long start;
public Calculate(long start, Storage storage) {
this.start = start;
this.storage = storage;
}
@Override
public void run() {
long num = start;
long sum = 0;
while (num <= 10000000) {
System.out.println(Thread.currentThread().getName() + " add num " + num);
sum += num;
num += 6;
}
// 线程计算完毕, 调用累加器进行累加
storage.push(sum);
}
}
/**
* 仓库对象,负责累加
*/
class Storage {
private long total = 0;
private int count = 0;
public synchronized void push(long sum) {
total += sum;
count++;
notifyAll();
}
public synchronized void printTotal() {
while (count < 6) {
try {
System.out.println(Thread.currentThread().getName() + " is wait");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("storage result = " + total);
}
}