【題意】:開6條線程計算累加1 -> 10000000多線程
【思路】:生產者-消費者 經典模型ide
/** * 多線程計算累加數 */ 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); } }