问题描述
现在主线程到了某个位置时创建并启动了3个子线程:t1、t2和t3,仅当t1、t2、t3都完成自己任务(比如它们都要计算1到100之和)之后主线程才能执行其下面的工作(比如将t1、t2和t3的运算结果加起来并输出)。请问该如何实现这个功能?听说好像要用到wait()、notify(),但不知道如何用到上面的例子上。
解决方案
t1.join()t2.join()t3.join()
解决方案二:
package org.demo.tmp;/** * 线程同步测试 * @author * @date 2010-12-5 * @file org.demo.tmp.Test.java */public class Test1 {/** * @param args */public static void main(String[] args)throws Exception {/* init 3 task [这里可直接用CountDownLatch]*/CountDown count = new CountDown(3);Task1 t1 = new Task1(count);Task1 t2 = new Task1(count);Task1 t3 = new Task1(count);/* init thread and start */new Thread(t1, "Thread one").start();new Thread(t2, "Thread two").start();new Thread(t3, "Thread three").start();/* wait all threads done */synchronized (count) {count.wait();}/* print the result */int result = t1.getTotal() + t2.getTotal() + t3.getTotal();System.out.println(">> result = " + result);}}/** * 用来计数的类 * @author */class CountDown {/* count */private int count;public CountDown(int value){this.count = value;}public void sub(int number){count -= number;}public int getValue(){return count;}}/** * 线程需要执行的任务 * @author */class Task1 implements Runnable{/* total */private int total = 0;/* count */private CountDown count;/** * constructor * @param count */public Task1(CountDown count){this.count = count;}@Overridepublic void run() {int sum = 0;for (int i=1; i<=100; i++){sum += i;}this.total = sum;System.out.println(Thread.currentThread().getName() + " done.");synchronized (count) {count.sub(1);if (count.getValue() <= 0){count.notify();}}}/** * get total value * @return */public int getTotal(){return total;}}
解决方案三:
引用仅当t1、t2、t3都完成自己任务(比如它们都要计算1到100之和)之后主线程才能执行其下面的工作CountDownLatch就能满足你的需求,用法也非常简单,你看看api里面给的例子。