多个线程并发执行完成后再执行主线程-java(简单版:使用join)

@Test
public void threadTest() throws Exception {
    int count = 10;
    List<Thread> threads = new ArrayList<>();
    for(int i = 0; i < count; i++) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("执行子线程");
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        threads.add(thread);
    }
    for(int i = 0; i < count; i++) {
        /** 等待线程执行完成(阻塞)
         * 阻塞状态(blocking):调用sleep方法,调用别的线程的join方法,执行I/O操做线程进入阻塞状态;
         * 解除阻塞:睡眠状态超时,调用join的线程执行完毕后,I/O操做完毕,调用阻塞线程的interrupt(中断)方法,会抛出
         * */
        threads.get(i).join();
    }
    System.out.println("执行主线程");
}
 ide

执行子线程Thread-13----:1534388413578
执行子线程Thread-14----:1534388413578
执行子线程Thread-15----:1534388413578
执行子线程Thread-16----:1534388413578
执行子线程Thread-17----:1534388413578
执行子线程Thread-18----:1534388413579
执行子线程Thread-19----:1534388413579
执行子线程Thread-20----:1534388413579
执行子线程Thread-21----:1534388413579
执行子线程Thread-22----:1534388413579
执行主线程main----:1534388423584
 spa

相关文章
相关标签/搜索