当尝试运行下面的程序时,它在“消耗中”后被挂起。
1 : 2 : 3 : 4 : 5 : 6 : 7 : 8 : 9 : 10 : object realsed
object .....realsed
in consume..
public class MyThreadNew {
public static void main(String[] args) {
Object obj=new Object();
boolean produce=true;
Thread t1=new Thread(new P(obj,produce));
Thread t2=new Thread(new C(obj,produce));
t1.start();
t2.start();
}
}
class P implements Runnable{
public Object obj;
public static boolean produce;
public P(Object obj, boolean produce){
this.obj=obj;
P.produce=produce;
}
public void produce(){
synchronized (obj) {
for(int i=1;i<=10;i++){
System.out.print(i+" : ");
}
C.produce=false;
obj.notifyAll();
System.out.println("object realsed");
}
System.out.println("object .....realsed");
}
public void run(){
produce();
}
}
class C implements Runnable{
public Object obj;
public static boolean produce;
public C(Object obj, boolean produce){
this.obj=obj;
C.produce=produce;
}
public void consume() throws InterruptedException{
while(true){
if(!C.produce){
System.out.println("in consume..");
synchronized (obj) {
obj.wait();
for(int i=1;i<=10;i++){
System.out.print("Consumed: "+i+" : ");
}
break;
}
}
}
}
public void run(){
try{
consume();
}catch (Exception e) {
e.printStackTrace();
}
}
}
我的程序出了什么问题?
最佳答案
如果带有 P
的线程首先启动,您将得到
for (int i = 1; i <= 10; i++) {
System.out.print(i + " : ");
}
C.produce = false;
然后,假设发生线程上下文切换,并且具有 C
的线程运行非同步
while (true) {
if (!C.produce) {
System.out.println("in consume..");
然后在同步
处阻塞。另一个线程再次开始,调用 notifyAll()
,然后离开其 synchronized
block 。 C
线程再次启动并调用
obj.wait();
阻止该应用,因为没有任何东西可以通知
它。
即使先启动 C
,它也无法继续执行 if
,并且您会得到相同的行为。
(另外,product
应该是 volatile
。)
关于java - 下面的程序有什么问题?Java wait/notify 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26891737/