java中Thread.join()

如果一个线程 A执行了 t h r e a d . j o i n ( )语句 ,
其含义是 :当前线程 A等待 t h r e a d线程终止之后才从 t h r e a d . j o i n ( )返回 。
线程 T h r e a d除了提供 j o i n ( )方法之外 ,
还提供了 j o i n ( l o n g m i l l i s )和
j o i n ( l o n g m i l l i s , i n t n a n o s )两个具备超时特性的方法 。
这两个超时方法表示 ,如果线程 t h r e a d在给定的超时时间里没有终止 ,
那么将会从该超时方法中返回 。

join()相当于给线程同步synchronized,加锁

public class Join {
    public static void main(String[] args) throws Exception {
        Thread previous = Thread.currentThread();
        for (int i = 0; i < 10; i++) {
            // 每个线程拥有前一个线程的引用,需要等待前一个线程终止,才能从等待中返回
            Thread thread = new Thread(new Domino(previous), String.valueOf(i));
            thread.start();
            previous = thread;
        }

        TimeUnit.SECONDS.sleep(5);
        System.out.println(Thread.currentThread().getName() + " 主 terminate.");
    }

    static class Domino implements Runnable {
        private Thread thread;

        public Domino(Thread thread) {
            this.thread = thread;
        }

        public void run() {
            try {
                thread.join();
            } catch (InterruptedException e) {
            }
            System.out.println(Thread.currentThread().getName() + " terminate.");
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值