多线程CountDownLatch和Join(2)

class ThreadDemo extends Thread{
    private int number;
    public ThreadDemo(int number){
        this.number = number;
    }
    public void run(){
        System.out.println("Thread"+number+" is running");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Thread"+number+"is end");
    }
}

运行结果如下:
 
Thread1 is running

Thread1is end

----

Thread2 is running

Thread2is end

main is end!

可以看到thread1阻塞了thread2,只有当thread1和thread2均执行结束后,main方法才能继续执行。如果想要thread1和thread2同时执行的话,只需要做如下简单的变动。

thread1.start();
thread1.join();
thread2.start();
thread2.join();
 
System.out.println("main is end!");

运行结果如下:
 
Thread1 is running

Thread2 is running

Thread1is end

Thread2is end

main is end!

因此,如果我们需要某些线程等待指定任务执行完毕之后执行,选择join方法也是一种选择;

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/a5d706806d22bf23aa71970c5ed99fe0.html