android:Thread.join()

来源:互联网 发布:java classpath 用法 编辑:程序博客网 时间:2024/05/14 00:34

使用场景:

存在两个线程,线程2的执行需要依赖线程1的完整数据,可利用join方法控制线程1结束后线程2再开始。

使用示例:

class ThreadTesterA implements Runnable {    private int counter;    @Override    public void run() {        while (counter <= 10) {            System.out.print("Counter = " + counter + " ");            counter++;        }        System.out.println();    }}class ThreadTesterB implements Runnable {    private int i;    @Override    public void run() {        while (i <= 10) {            System.out.print("i = " + i + " ");            i++;        }        System.out.println();    }}public class ThreadTester {    public static void main(String[] args) throws InterruptedException {        Thread t1 = new Thread(new ThreadTesterA());        Thread t2 = new Thread(new ThreadTesterB());        t1.start();        t1.join(); // wait t1 to be finished        t2.start();        t2.join(); // in this program, this may be removed    }}

t1启动后,调用join()方法,直到t1的计数任务结束,才轮到t2启动,然后t2也开始计数任务。可以看到,实例中,两个线程就按着严格的顺序来执行了。


转载自:http://blog.csdn.net/hustpzb/article/details/8472929

0 0
原创粉丝点击