![](/img/trans.png)
[英]Java. The method isOpen() is undefined for the type Lock. Also need some help fixing some code/debugging
[英]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.