java中Thread.join()

来源:互联网 发布:数据重复怎么筛选出来 编辑:程序博客网 时间:2024/06/15 08:05

如果一个线程 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.");        }    }}
0 0
原创粉丝点击