【发布时间】:2016-08-05 16:11:19
【问题描述】:
我正在尝试使用等待通知的 2 个线程生成奇数/偶数。
但它只是打印 1。
下面是代码:
Even.java
public class Even implements Runnable {
private int i; private Object ob
public Even(int i,Object o) {
this.i=i;
this.ob=o;
}
@Override
public void run() {
while (true) {
synchronized (ob) {
while (i % 2 == 0) {
try {
ob.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
i++;
System.out.println(i);
ob.notifyAll();
}
}
}
}
Odd.java
public class Odd implements Runnable {
private int i; private Object ob;
public Odd(int i) {
this.i=i;
this.ob=o;
}
@Override
public void run() {
while (true) {
synchronized (ob) {
while (i % 2 == 1) {
try {
ob.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
i++;
System.out.println(i);
ob.notifyAll();
}
}
}
}
Test.java
public class Test {
public static void main(String[] args) {
int i = 0;
Object lock = new Object();
Thread t1 = new Thread(new Even(i),lock);
Thread t2 = new Thread(new Odd(i),lock);
t1.start();
t2.start();
}
}
输出:
1
谁能告诉我哪里出错了?
【问题讨论】:
-
您的
Odd构造函数缺少o参数。而且您将lock传递给您的线程构造函数,而不是传递给您的runnables。也许发布一些可以编译的东西。 -
你的内部
while循环没有意义,并且会无限循环,因为i不在线程之间共享。 -
如果您尝试调试代码,您会清楚地看到发生了什么以及为什么。
标签: java multithreading synchronization wait notify