我有以下课程

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

    ThreadDemo( String name) {
        threadName = name;
    }

    public void run() {
        for(int i = 5; i > 0; i--) {
            System.out.println("Thread " +  threadName + " Counter   ---   "  + i );
        }

        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            System.out.println("Sleep issue");
        }

        System.out.println("Finishing run");

        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            System.out.println("Sleep issue");
        }
    }

    public void start () {
        t = new Thread (this, threadName);
        t.start ();
    }
}


如下测试

public class Main {
    public static void main(String[] args) {
        ThreadDemo T1 = new ThreadDemo( "Thread - 1 ");
        ThreadDemo T2 = new ThreadDemo( "Thread - 2 ");
        T1.start();
        T2.start();

        //Let's give some time for threads to run
        try {
            Thread.sleep(10);
        } catch (Exception e) {
            System.out.println("Main sleep issue");
        }

        try {
            T1.join();
            T2.join();
        } catch ( Exception e) {
            System.out.println("Interrupted");
        }

        System.out.println("Finishing main.");
    }
}


为什么尽管我使用T1.join()和T2.join()等待它们完成,但为什么我总是在输出“ Finishing run”之前得到“ Finishing main”?最初,我认为这可能是由于缓冲区延迟所致,所以我在run()的末尾添加了Thread.sleep(1000)以便花一些时间来打印“ Finishing run”,但这并没有帮助。我猜这是由于Thread.sleep(1000)的第一次出现(当我删除它时,它的工作正常),但不知道为什么。

最佳答案

因为这个:

public void start () {
    t = new Thread (this, threadName);
    t.start ();
}


因此,您的ThreadDemo实例实际上不会真正作为线程启动:打印Finishing run消息的线程就是在该方法中创建的线程。该线程与ThreadDemo之间没有链接。

删除start()方法。

关于java - java Thread.join无法按预期工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47443975/

10-12 00:27
查看更多