简体   繁体   English

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

[英]Main not waiting for threads even after using Thread.join() in Java

join() is supposed to make main function wait until all the threads complete execution, but main is printing completed before Thread-1 and Thread-2 completes execution. join()应该使main函数等待所有线程完成执行,但是main在Thread-1Thread-2完成执行之前completed打印。 I am unable to find error in the code. 我在代码中找不到错误。 where's the mistake? 哪里错了?

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");
    }
}

Output 输出量

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

You're joining on the ThreadDemo instances. 您正在加入ThreadDemo实例。 But you're not running these instances as threads. 但是您没有将这些实例作为线程运行。 Your overridden start method creates and starts another Thread. 您重写的start方法创建并启动另一个线程。

Your code is extremely convoluted. 您的代码非常复杂。 You use both inheritance and delegation, and you override methods and break their contract: start() is supposed to start this as a thread, not create and start another thread. 您同时使用了继承和委托,并且重写了方法并破坏了它们的约定:start()应该以一个线程的形式启动this ,而不是创建并启动另一个线程。

Here's what it should look like: 它应该是这样的:

class ThreadDemo implements Runnable {
    private String threadName;

    ThreadDemo(String name) {
        this.threadName = name;
    }

    @Override
    public void run() {
        System.out.println("Thread " + threadName + " exiting.");
    }

}
public class Problem2 {
    public static void main(String[] args) {
        ThreadDemo runnable1 = new ThreadDemo("Thread-1");
        ThreadDemo runnable2 = new ThreadDemo("Thread-2");

        Thread t1 = new Thread(runnable1);
        Thread t2 = new Thread(runnable2);

        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            System.out.println("ERROR!");
        }
        System.out.println("completed");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM