java - 下面的程序有什么问题?Java wait/notify 不起作用

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

我的程序出了什么问题?

最佳答案

如果带有 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/

相关文章:

javascript - 使用 Promise.all 通过 Puppeteer 实现某种多线程

java - 不知道如何设置背景图像

java - 如何创建具有扩展另一个类并实现接口(interface)的类型参数的基本适配器?

c# - 延迟加载和Thread.MemoryBarrier的使用

c# - 在Windows服务中使用计时器

c++ - 在 std::cin 上发送输入

multithreading - Matlab中的多线程稀疏矩阵乘法

oracle - java安全异常: sealing violation while trying to connect to database

java - JavaSparkContext.wholeTextFiles 的数据集 API 模拟

java - 将从 URL 输出的 JSON 保存到文件