让一个线程等待另一个线程完成

时间:2014-11-23 07:21:22

标签: java multithreading

我有两个线程类:一个打印0到9之间的数字,另一个打印100到109.我想要的是让第一个线程等待另一个完成。为此,我使用了join()方法,但它不起作用。请告诉我我哪里出错:

//demonstrates the use of join() to wait for another thread to finish
class AThread implements Runnable {
    Thread t;

    AThread() {
        t = new Thread(this);
    }

    public void run() {
        try {
            for (int i=0; i<10; i++) {
                System.out.println(i);
                Thread.sleep(10);
            }
        } catch (InterruptedException e) {
            System.out.println(t + " interruped.");
        }
    }

    public void halt(Thread th) {
        try {
            th.join();
        } catch (InterruptedException e) {
            System.out.println(t + " interruped.");
        }
    }
}

//a different thread class (we distinguish threads by their output)
class BThread implements Runnable {
    Thread t;

    BThread() {
        t = new Thread(this);
    }

    public void run() {
        try {
            for (int i=100; i<110; i++) {
                System.out.println(i);
                Thread.sleep(10);
            }
        } catch (InterruptedException e) {
            System.out.println(t + " interruped.");
        }
    }
}

public class WaitForThread {
    public static void main(String[] args) {
        AThread t1 = new AThread();
        BThread t2 = new BThread();

        t1.t.start();
        t1.halt(t2.t); //wait for the 100-109 thread to finish
        t2.t.start();
    }
}

1 个答案:

答案 0 :(得分:3)

在线程启动前调用join。这不起作用;在这种情况下,join将立即返回,它不会等到另一个线程启动并稍后停止。您可以在API文档中看到这一点:

Thread.join()

  

此实现使用以this.wait为条件的this.isAlive调用循环。

Thread.isAlive()

  

测试此线程是否存活。如果线程已经启动,则该线程仍处于活动状态并且尚未死亡。

重新排序main方法

中的语句
t1.t.start();
t2.t.start();
t1.halt(t2.t); //wait for the 100-109 thread to finish

编辑在评论中回答您的问题:

如果您希望AThread中的帖子在完成工作之前等待BThread中的帖子完成,那么您需要在join中拨打AThread.run ,并更改您的main方法:

class AThread implements Runnable {
    Thread t;
    Thread threadToWaitFor;

    AThread(Thread threadToWaitFor) {
        t = new Thread(this);
        this.threadToWaitFor = threadToWaitFor;
    }

    public void run() {
        // First wait for the other thread to finish
        threadToWaitFor.join();

        // ...
    }

    // ...
}

public class WaitForThread {
    public static void main(String[] args) {
       BThread t2 = new BThread();
       AThread t1 = new AThread(t2.t);

        t2.t.start();
        t1.t.start();
    }
}