繁体   English   中英

Java:wait()不会释放锁定。 为什么?

[英]Java: wait() doesnt free lock. Why?

我的代码在“生产者启动”处停止。 为什么wait()无法释放锁? 我在同步部分中使用了相同的对象,但是它不起作用。

class Processor {
    public void produce() throws InterruptedException {
        synchronized (this) {
            System.out.println("Producer started");
            wait();
            System.out.println("Producer ended");
        }
    }

    public void consume() throws InterruptedException {
        System.out.println("Consumer started");
        Scanner scanner = new Scanner(System.in);
        synchronized (this) {
            scanner.nextLine();
            System.out.println("go to producer");
            notify();
            Thread.sleep(1000);
            System.out.println("Consumer ended");
        }
    }
}

当我在不同线程中运行此代码时,我正在使用相同的Processor对象

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Processor processor = new Processor();

        Thread t1 = new Thread(() -> {
            try {
                processor.produce();
            } catch (InterruptedException e) {}
        });

        Thread t2 = new Thread(() -> {
            try {
                processor.consume();
            } catch (InterruptedException e) {}
        });

        t1.run();
        t2.run();
        t1.join();
        t2.join();
    }
}

也许尝试:

t1.start ();
t2.start ();

代替

t1.run ();
t2.run ();

这里的问题是您在线程上调用run()方法。 如果要在单独的线程中运行,请使用start()。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM