美文网首页
Thread::join()

Thread::join()

作者: 四喜汤圆 | 来源:发表于2020-06-07 23:10 被阅读0次

一、作用

现有线程对象threadB,在线程 A 中调用threadB.join(),那么当线程 B 终止后,方法threadB.join()才返回。

活生生地把一个异步的整成了同步任务

二、概念

三、使用

10个线程,编号0-9,让这10个线程按照编号顺序执行

public class JoinTest {
    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 mThread;

        public Domino(Thread thread) {
            mThread = thread;
        }

        @Override
        public void run() {
            try {
                mThread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" terminate.");
        }
    }
}

参考文献

join()

相关文章

网友评论

      本文标题:Thread::join()

      本文链接:https://www.haomeiwen.com/subject/dkxktktx.html