java 为什么notify和notifyAll都不起作用?
本文介绍了java 为什么notify和notifyAll都不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
class Example{
public static void main(String arr[]){
ThreadB th1=new ThreadB("th1");
ThreadB th2=new ThreadB("th2");
}
}
class ThreadB implements Runnable{
C c;
Thread thread;
ThreadB(String name){
c=new C();
thread=new Thread(this,name);
thread.start();
}
public void run(){
if(thread.getName().equals("th1")){
for(int i=0;i<3;i++)c.t1(false);
c.t1(true);
}
if(thread.getName().equals("th2")){
for(int i=0;i<3;i++)c.t2(false);
c.t2(true);
}
System.out.println("end");
}
}
class C{
synchronized void t1(boolean boo){
if(boo){
notify();
return;
}
System.out.println("t1");
notify();
try{
wait();
}catch(InterruptedException exc){System.out.println(exc);}
}
synchronized void t2(boolean boo){
if(boo){
System.out.println();notify();return;
}
System.out.println("t2");
notify();//notifyAll()也没效果;
}
}
调用了notify()无法唤醒th1线程。
解决方案
每个线程初始化的时候都是 c=new C(),锁住的是不同的对象。
class Example{
public static void main(String arr[]){
C c = new C();
ThreadB th1=new ThreadB("th1",c);
ThreadB th2=new ThreadB("th2",c);
}
}
class ThreadB implements Runnable{
C c;
Thread thread;
ThreadB(String name,C c){
//c=new C();
this.c=c;
thread=new Thread(this,name);
thread.start();
}
public void run(){
if(thread.getName().equals("th1")){
for(int i=0;i<3;i++)c.t1(false);
c.t1(true);
}
if(thread.getName().equals("th2")){
for(int i=0;i<3;i++)c.t2(false);
c.t2(true);
}
System.out.println("end");
}
}
class C{
synchronized void t1(boolean boo){
if(boo){
notify();
return;
}
System.out.println("t1");
notify();
try{
wait();
}catch(InterruptedException exc){System.out.println(exc);}
}
synchronized void t2(boolean boo){
if(boo){
System.out.println();notify();return;
}
System.out.println("t2");
notify();//notifyAll()也没效果;
}
}
这篇关于java 为什么notify和notifyAll都不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文