Java等待和通知导致死锁
我想一个接一个地运行两个线程,而不使用sleep()或锁,但会发生死锁!我的代码怎么了?我使用wait()和notifyAll()以及一个对象Java等待和通知导致死锁,java,multithreading,Java,Multithreading,我想一个接一个地运行两个线程,而不使用sleep()或锁,但会发生死锁!我的代码怎么了?我使用wait()和notifyAll()以及一个对象 public class Test { public static void main(String[] args) throws InterruptedException { PrintChar a = new PrintChar('a'); PrintChar b = new PrintChar('b');
public class Test {
public static void main(String[] args) throws InterruptedException {
PrintChar a = new PrintChar('a');
PrintChar b = new PrintChar('b');
Thread ta = new Thread(a);
Thread tb = new Thread(b);
ta.start();
tb.start();
}
}
class PrintChar implements Runnable {
final Object o = new Object();
char ch;
public PrintChar(char a) {
ch = a;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
synchronized (o) {
System.out.print(ch);
try {
o.wait();
o.notifyAll();
} catch (InterruptedException ex) {
}
}
}
}
}
公共类测试{
公共静态void main(字符串[]args)引发InterruptedException{
PrintChar a=新的PrintChar('a');
PrintChar b=新的PrintChar('b');
螺纹ta=新螺纹(a);
线程tb=新线程(b);
ta.start();
tb.start();
}
}
类PrintChar实现可运行{
最终对象o=新对象();
char ch;
公共打印字符(字符a){
ch=a;
}
@凌驾
公开募捐{
对于(int i=0;i<100;i++){
同步(o){
系统输出打印(ch);
试一试{
o、 等待();
o、 notifyAll();
}捕获(中断异常例外){
}
}
}
}
}
我认为synchronized
块导致了死锁。因为在当前线程完成之前,它不会让另一个线程启动。您正在使用wait()
方法使当前线程等待。好的,它将等待,但由于它在同步
块中,因此它将永远在当前线程中,不会因为同步
而让任何其他线程存在
要使另一个线程正常工作,可以使用
thread.stop
。尝试在当前线程的引用中调用stop方法
。但是我不确定它是否会让当前线程重新启动。运行您的代码,查看它,我发现您生成的每个线程都在生成并同步到它自己的对象,因此阻止它们相互通知。我还发现,在notify之前需要等待,因此您永远无法调用o.notifyAll()
,因为o.wait()
会先停止它
将
final Object o=new Object()
更改为static final Object o=new Object()
,并切换o.wait()
和o.notifyAll()的位置,但这肯定会根据您的问题启动其他线程,而不使用sleep():)这是错误的,因为Object.wait()的函数有一半是错误的
是以原子方式释放其上的锁。它实际上需要在所讨论的对象上的synchronized
块中调用。我从来都不理解这些问题。如果您想要顺序执行,为什么要使用线程?更不用说EJP了!只是练习!