Java并发编程初级篇(四):等待子线程终止

原创
2016/11/23 11:36
阅读数 140

我们先看一个例子,在这个例子中你会发现主线程结束后,过了一段时间两个子线程才结束。

定义实现Runnable接口的线程类,模拟执行一定时间后结束。

public class MyRunnable implements Runnable{
    @Override
    public void run() {
        System.out.printf("%s: I am start working.\n", Thread.currentThread().getName());
        try {
            TimeUnit.SECONDS.sleep((long) (Math.random() * 10 + 1));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("%s: I am end working.\n", Thread.currentThread().getName());
    }
}

定义主方法,启动两个子线程:

public class Main {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new MyRunnable());
        Thread thread2 = new Thread(new MyRunnable());

        System.out.printf("%s: start two threads.\n", Thread.currentThread().getName());
        thread1.start();
        thread2.start();
        System.out.printf("%s: end.\n", Thread.currentThread().getName());
    }
}

查看控制台日志,你会发现主线程先于两个子线程而结束。

main: start two threads.
main: end.
Thread-1: I am start working.
Thread-0: I am start working.
Thread-1: I am end working.
Thread-0: I am end working.

当你想让主线程等待所有子线程执行结束后,再执行一段代码才结束,应该怎么做呢。Java提供了join()方法。我们重写主方法,在主方法中调用子线程的join()方法,即可让主线程进入WAITING状态并等待子线程终止后继续执行。

public class Main {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new MyRunnable());
        Thread thread2 = new Thread(new MyRunnable());

        System.out.printf("%s: start two threads.\n", Thread.currentThread().getName());
        thread1.start();
        thread2.start();

        try {
            thread2.join();
            thread1.join();
            System.out.printf("%s: child runnable both ends.\n", Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.printf("%s: end.\n", Thread.currentThread().getName());
    }
}

查看控制台日志,你会发现主线程在等待两个子线程终止之后才继续执行。

main: start two threads.
Thread-0: I am start working.
Thread-1: I am start working.
Thread-0: I am end working.
Thread-1: I am end working.
main: child runnable both ends.
main: end.

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部