该列子的作用是:想让两个子线程分别执行完成后再执行main线程。
package org.demo.temp;
/**
* 线程同步测试
* @author
* @date 2010-12-5
* @file org.demo.tmp.Test.java
*/
public class Test1 {
/**
* @param args
*/
public static void main(String[] args)throws Exception {
// 参数3是对三个子线程执行完毕的计数器,在run方法中进行扣减
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);
System.out.println(">>count.value = " +count.getValue());
}
}
/**
* 用来计数的类
* @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;
}
public 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;
}
}