Sou*_*abh 7 java multithreading thread-safety
奇数偶数打印使用thread.Create一个线程类,两个线程实例.一个将打印奇数,另一个将打印偶数.
我做了以下编码.但它涉及死锁状态.有人可以解释一下可能是什么原因吗?
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();
}
}
Run Code Online (Sandbox Code Playgroud)
Out Put: odd1 even2
然后陷入僵局!!!!!!
谢谢你的帮助.
aio*_*obe 13
您正在等待并通知不同的对象(监视器).
这个想法是,你可以调用obj.wait()
等待有人做obj.notify()
,而你正在做的objA.wait()
和objB.notify()
.
将您的printOdd
方法更改为类似的方法
private void printOdd(int i) {
synchronized (lock) { // <-------
while (!oddTurn) {
try {
lock.wait(); // <-------
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(type + i);
oddTurn = false;
lock.notifyAll(); // <-------
}
}
Run Code Online (Sandbox Code Playgroud)
和printEven
方法类似.
然后提供NumberPrinter
一个lock
对象:
Object lock = new Object();
Thread odd = new Thread(new NumberPrinter("odd", lock));
Thread even = new Thread(new NumberPrinter("even", lock));
Run Code Online (Sandbox Code Playgroud)
输出:
odd1
even2
odd3
even4
odd5
even6
odd7
even8
odd9
Run Code Online (Sandbox Code Playgroud)