即使在Java中使用Thread.join()之后,Main也不会等待线程

时间:2018-09-15 15:49:37

标签: java concurrency java-threads

join()应该使main函数等待所有线程完成执行,但是main在completedThread-1完成执行之前打印Thread-2。 我在代码中找不到错误。错误在哪里?

class ThreadDemo extends Thread {
    private Thread t;
    private String threadName;

    ThreadDemo(String name) {
        threadName = name;
    }
    public void run() {
        System.out.println("Thread " + threadName + " exiting.");
    }
    public void start() {
        if (t == null) {
            t = new Thread (this, threadName);
            t.start();
        }
    }
}
public class Problem2 {
    public static void main(String[] args) {
        ThreadDemo T1 = new ThreadDemo("Thread-1");
        ThreadDemo T2 = new ThreadDemo("Thread-2");
        T1.start();
        T2.start();
        try {
            T1.join();
            T2.join();
        } catch (InterruptedException e) {
            System.out.println("ERROR!");
        }
        System.out.println("completed");
    }
}

输出

completed
Thread Thread-2 exiting.
Thread Thread-1 exiting.

1 个答案:

答案 0 :(得分:3)

您正在加入ThreadDemo实例。但是您没有将这些实例作为线程运行。您覆盖的start方法将创建并启动另一个线程。

您的代码非常复杂。您同时使用继承和委托,并覆盖了方法并破坏了它们的约定:start()应该以{{1​​}}作为线程启动,而不是创建并启动另一个线程。

它应该是这样的:

this