Java: wait() 不释放锁。为什么?
Java: wait() doesnt free lock. Why?
我的代码停在 "Producer started"。为什么 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");
}
}
}
虽然我运行这段代码在不同的线程中,但我使用的是同一个处理器对象
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 ();
这里的问题是您在线程上调用了 运行() 方法。如果您要在单独的线程中 运行 ,则应该使用 start() 。
我的代码停在 "Producer started"。为什么 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");
}
}
}
虽然我运行这段代码在不同的线程中,但我使用的是同一个处理器对象
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 ();
这里的问题是您在线程上调用了 运行() 方法。如果您要在单独的线程中 运行 ,则应该使用 start() 。