【发布时间】: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