让子线程执行完后再执行主线程的列子

该列子的作用是:想让两个子线程分别执行完成后再执行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;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值