Thread.join()的使用

返回主页面

package com.qdb.thinkv.thread.base.join;

import java.sql.SQLNonTransientConnectionException;
import java.util.concurrent.TimeUnit;

public class ThreadJoinv2 {
    
    public static void main(String[] args) throws InterruptedException {
        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) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" terminate.");
        }
        
    }
}

执行结果:

这是 join 的源码

当线程终止时,会调用线程自身的notitfyAll()方法,会通知所有等待在该对象上的线程。

猜你喜欢

转载自www.cnblogs.com/tianzhiyun/p/9463694.html
今日推荐