我已经使用 wait() 和 notify() 机制了解了 java 中的多线程。但我对一个简单的多线程 java 应用程序的输出非常好奇。 下面的代码:
class Q {
int n;
boolean valueSet = false;
synchronized int get() {
if (!valueSet) {
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
if (valueSet) {
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}
class Producer implements Runnable {
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while (true) {
q.put(i++);
}
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while (true) {
q.get();
}
}
}
class PCFixed {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
拳头,我运行该应用程序,然后单击调试工具中的“停止”按钮停止应用程序。这会产生两个“奇怪的输出”:这是第一次运行应用程序的输出:
这是应用程序第二次运行的输出:
为什么我们有两个重复的输出行:“put:13177”
为什么我们在另一个时间有两个重复的输出行:“got: 2713” 。
这个结果让我很困惑!!一些机构可以帮助我理解这个问题!感谢先进。