【发布时间】:2011-08-26 09:55:41
【问题描述】:
奇偶数打印使用线程。创建一个线程类,两个线程实例。一个打印奇数,另一个打印偶数。
我做了以下编码。但它涉及死锁状态。有人可以解释一下这可能是什么原因吗?
public class NumberPrinter implements Runnable{
private String type;
private static boolean oddTurn=true;
public NumberPrinter(String type){
this.type=type;
}
public void run() {
int i=type.equals("odd")?1:2;
while(i<10){
if(type.equals("odd"))
printOdd(i);
if(type.equals("even"))
printEven(i);
i=i+2;
}
}
private synchronized void printOdd(int i){
while(!oddTurn){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(type + i);
oddTurn=false;
notifyAll();
}
private synchronized void printEven(int i){
while(oddTurn){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(type + i);
oddTurn=true;
notifyAll();
}
public static void main(String[] s){
Thread odd=new Thread(new NumberPrinter("odd"));
Thread even=new Thread(new NumberPrinter("even"));
odd.start();
even.start();
}
}
输出: 奇数1 偶数2
然后陷入僵局!!!!!!
感谢您的帮助。
【问题讨论】:
-
这是作业吗?如果是这样,请将标签“作业”添加到您的问题中。
-
为什么是这个标记算法?
标签: java multithreading thread-safety