【发布时间】:2014-12-09 01:30:54
【问题描述】:
我正在尝试使用如下所示的两个线程来执行此操作。有人能指出我在这里犯的明显错误吗?
public class OddEven {
public static boolean available = false;
public static Queue<Integer> queue = new LinkedList<Integer>();
static Thread threadEven = new Thread() {
@Override
public void run() {
printEven();
}
public synchronized void printEven() {
while (!available) {
try {
wait();
Thread.sleep(2000);
} catch (InterruptedException e) {
}
}
System.out.println(queue.remove());
available = false;
notifyAll();
}
};
static Thread threadOdd = new Thread() {
@Override
public void run() {
printOdd();
}
public synchronized void printOdd () {
while (available) {
try {
wait();
Thread.sleep(2000);
} catch (InterruptedException e) {
}
}
System.out.println(queue.remove());
available = true;
notifyAll();
}
};
public static void main(String[] args) {
int n = 20;
for (int i = 1; i < n; i++) {
queue.add(i);
}
threadOdd.start();
threadEven.start();
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
threadOdd.join();
threadEven.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
但是这个程序只打印 1 并退出。打印 1 后,available 应该为 true,printEven 应该唤醒、打印并将 available 设置为 false。我不明白这里出了什么问题?我看到了其他解决方案,但想知道为什么我的解决方案不起作用。
【问题讨论】:
-
虽然这是一个流行的练习(虽然我不明白为什么),但 OP 代码的问题与发布的链接中的问题不同。因此,除非我错过了什么,否则我认为将其作为这些链接的副本关闭是没有用的。 (由于这是一个非常常见的错误,因此可能存在另一个链接,这可能是一个骗局。)
标签: java multithreading static java-threads