Java 中多线程等待通知示例中的 Thread join(1) 用法

Thread join(1) usage in mutlithread wait-notify example in Java

我有一个从 main 调用的等待通知应用程序示例:

public class Handler {

public void producer () throws InterruptedException {
    Thread.sleep(1000);
    synchronized(this) {
        System.out.println("Producer started ######...");
        wait();
        System.out.println("Proceed running in current thread after notification and 5s sleep in consumer tread");
    }
}

public void consumer() throws InterruptedException {
    Thread.sleep(2000);
    synchronized(this) {
        System.out.println("Consumer started #####...");
        notify();
        Thread.sleep(5000);
    }

}

}

和调用者

public class ThreadRunner {

public static void main(String[] args) {
    
    Handler handler = new Handler();
    
    Thread thread1 = new Thread(() -> {
        try {
            handler.producer();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    
    Thread thread2 = new Thread(() -> {
        try {
            handler.consumer();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
    thread1.start();
    thread2.start();
    
    
    try {
        thread1.join(1);
        thread2.join(1);
    } catch (InterruptedException e) {
    System.out.println("exception");
    }
}

}

正如我所料,“异常”消息应该在我加入(1)到线程并等待它们仅死去 1 个磨坊时打印出来,但它们的睡眠时间不止于此。我错过了什么?

join(1) 有 3 种方式 'out':

  • 您调用 join 的线程结束,在这种情况下,您对 join(1) 的调用通过返回停止 运行。
  • 某处的一些代码(它是唯一可以做到这一点的代码,例如用户按 CTRL+C 或诸如此类的东西永远不会导致这种情况)在您的线程上调用 .interrupt()join(1) 通过抛出 InterruptedException.
  • 停止 运行
  • 1 毫秒过去了,在这种情况下 join(1) 通过返回停止 运行。

你的印象显然是,如果时间用完,join 方法会通过抛出 InterruptedEx 的方式退出。它没有。