java - 使用独立的 wait() 方法和使用类的任何实例( obj.wait() )有什么区别
问题描述
我正在尝试以交错方式执行 2 个线程。一个是打印奇数,另一个是打印偶数到控制台(<=100)。我希望输出为:1 2 3 4 5 6 7 8 9 10 .... 等等。即他们应该按顺序一个接一个地执行。
这是此的代码:
class Monitor{
boolean flag = false;
}
class OddNumberPrinter implements Runnable{
Monitor monitor;
OddNumberPrinter(Monitor monitor){
this.monitor = monitor;
}
@Override
public void run() {
for (int i = 1; i<100; i+=2){
synchronized (monitor){
while(monitor.flag == true){
try {
wait();
} catch (Exception e) {}
}
System.out.print(i+" ");
monitor.flag = true;
notify();
}
}
}
}
class EvenNumberPrinter implements Runnable{
Monitor monitor;
EvenNumberPrinter(Monitor monitor){
this.monitor = monitor;
}
@Override
public void run() {
for (int i = 2; i<101; i+=2){
synchronized (monitor){
while (monitor.flag == false){
try {
wait();
} catch (Exception e) {}
}
System.out.print(i + " ");
monitor.flag = false;
notify();
}
}
}
}
public class InterleavingThreads {
public static void main(String[] args) throws InterruptedException {
Monitor monitor = new Monitor();
Thread t1 = new Thread(new OddNumberPrinter(monitor));
Thread t2 = new Thread(new EvenNumberPrinter(monitor));
t1.start();
t2.start();
}
}
当我独立使用wait() 和 notify()时,它会引发异常,但使用 monitor.wait() 和 monitor.notify()会给出正确的输出。请解释这两者的区别。
解决方案
推荐阅读
- ios - 使用 Shell 的 iPad 不会填充纵向,但会缩放到横向
- ruby-on-rails - 在 Ruby 中转换时间(Sinatra 框架)
- c - CBMC:抛出:“分支之间的原子部分不同”
- android - l'API SMS Retriever 的空哈希值
- mongodb - 有没有办法在不同的会话中查看查询历史,Robo3t
- python - 任何人都可以帮我用 PySimpleGUI 编写代码来完成这个
- python - Cython 无法转换为 Python 对象
- python - 使用 python 从网络读取有效负载请求
- solr - 记录没有被删除使用
cloudsolrclient 中的功能 - javascript - Ngx-Leaflet:在地图上反转图层渲染