以下程序有什么问题?Java wait / notify无效

时间:2014-11-12 16:26:01

标签: java multithreading

在试图低于程序时,它会在“消耗”之后被绞死。

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();
        }
    }
}

我的程序出了什么问题?

1 个答案:

答案 0 :(得分:5)

如果首先启动P的主题,则

for (int i = 1; i <= 10; i++) {
    System.out.print(i + " : ");
}
C.produce = false;

然后,假设线程上下文切换发生,而C的线程运行un - synchronized

while (true) {
    if (!C.produce) {
        System.out.println("in consume..");

然后阻止synchronized。另一个线程再次开始,调用notifyAll(),然后离开其synchronized块。 C的帖子再次启动并调用

obj.wait();

阻止该应用,因为notify没有留下任何内容。

即使C首先启动,它也无法超越if并且您获得相同的行为。

(另请注意,produce应为volatile。)