サブスレッドを実行させてからメインスレッドの列を実行します.
2634 ワード
このカラムの役割は、2つのサブスレッドをそれぞれ実行して完了した後に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;
}
}