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

问题描述 投票:-1回答:1

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.
java concurrency java-threads
1个回答
3
投票

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

你的代码非常错综复杂。你使用继承和委托,你重写方法并打破他们的合同:start()应该启动this作为一个线程,而不是创建和启动另一个线程。

这是它应该是什么样子:

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");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.