【问题标题】:Thread join(1) usage in mutlithread wait-notify example in JavaJava中多线程等待通知示例中的线程连接(1)用法
【发布时间】:2021-12-16 22:07:55
【问题描述】:

我有一个从 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 磨机时,应该打印“异常”消息,但它们的睡眠时间不止于此。我错过了什么?

【问题讨论】:

    标签: java multithreading concurrency


    【解决方案1】:

    join(1) 有 3 种“退出”方式:

    • 您调用join 的线程结束,在这种情况下,您对join(1) 的调用通过返回停止运行。
    • 某处的某些代码(它只是可以执行此操作的代码,例如,用户按 CTRL+C 或其他不会导致此问题的代码)在您的线程上调用 .interrupt(); join(1) 通过抛出 InterruptedException 停止运行。
    • 经过 1 毫秒,在这种情况下,join(1) 通过返回停止运行。

    您显然认为如果时间用完,join 方法会以抛出 InterruptedEx 的方式退出。它没有。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-31
      相关资源
      最近更新 更多