【发布时间】:2021-04-21 19:18:25
【问题描述】:
为了理解 wait() 和 notifyAll() 功能,我正在创建一个程序来更好地理解所提到的多线程概念。但不知何故,我注意到以下程序在通过 Thread 类工作并产生预期输出时运行良好。但是当我用 Runnable 接口切换同一个程序时,我遇到了死锁问题。
任何我哪里出错的建议或者我对这个概念缺乏什么理解。
class Test{
public static void main(String[] args) {
Notifier notifier = new Notifier();
new Waiter(notifier, "A").start();
new Waiter(notifier, "B").start();
notifier.start();
}
}
Waiter 类在不同线程上调用 wait()。
class Waiter extends Thread{
private Notifier notifier;
Waiter(Notifier notifier, String name){
super(name);
this.notifier = notifier;
}
public void run(){
synchronized(notifier){
System.out.println(Thread.currentThread().getName() + " is trying to call wait()");
try{
notifier.wait();
}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName() + " will now continue with remaining code");
}
}
}
Notifier 类调用 notifyAll() 并通知所有等待的线程。
class Notifier extends Thread{
public void run(){
synchronized(this){
try{
Thread.sleep(100);
}catch(InterruptedException e){}
System.out.println("Notifying all threads");
notifyAll();
}
}
}
以下程序的O/P是
A is trying to call wait()
B is trying to call wait()
Notifying all threads
B will now continue with remaining code
A will now continue with remaining code
现在同一个程序使用可运行接口
class Test{
public static void main(String[] args) {
Notifier notifier = new Notifier();
// new Waiter(notifier, "A").start();
// new Waiter(notifier, "B").start();
//
// notifier.start();
new Thread(new Waiter(notifier), "A").start();
new Thread(new Waiter(notifier), "B").start();
new Thread(notifier).start();
}
}
class Waiter implements Runnable{
private Notifier notifier;
Waiter(Notifier notifier){
// super(name);
this.notifier = notifier;
}
public void run(){
synchronized(notifier){
System.out.println(Thread.currentThread().getName() + " is trying to call wait()");
try{
notifier.wait();
}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName() + " will now continue with remaining code");
}
}
}
class Notifier implements Runnable{
public void run(){
synchronized(this){
try{
Thread.sleep(100);
}catch(InterruptedException e){}
System.out.println("Notifying all threads");
notifyAll();
}
}
}
以下程序的O/P导致死锁情况
A is trying to call wait()
Notifying all threads
B is trying to call wait()
A will now continue with remaining code
我试图通过使主线程休眠 1ms 并获得所需的输出,在 1 毫秒后启动通知程序线程。
new Thread(new Waiter(notifier), "A").start();
new Thread(new Waiter(notifier), "B").start();
try{
Thread.sleep(1);
}catch(InterruptedException e){}
new Thread(notifier).start();
但是为什么在正常/顺序启动通知程序线程时它不起作用(即没有休眠)。是因为我正在为 Runnable 目的或其他目的创建额外的对象吗?
【问题讨论】:
标签: java multithreading