[英]java deadlock while printing sequence using two threads
我嘗試使用兩個線程打印奇數和偶數。 但是程序進入了僵局。 我不明白為什么它會陷入僵局。 在調試模式下,程序的行為不同。 它打印 1 2 然后死鎖。 這種行為是意外的。
預期產出
1
2
3
4
odd thread ends here
even thread ends here
main thread ends here
電流輸出
1
2
3
4
odd thread ends here
(Deadlock)
這是java代碼
public class PrintSequence {
public static void main(String[] args) {
EvenOddPrinter printer = new EvenOddPrinter(false, 1, 4);
Thread odd = new Thread(new Runnable() {
@Override
public void run() {
printer.printOdd();
}
});
Thread even = new Thread(new Runnable() {
@Override
public void run() {
printer.printEven();
}
});
odd.start();
even.start();
try {
odd.join();
System.out.println("odd thread ends here");
even.join();
System.out.println("even thread ends here");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main thread ends here");
}
}
class EvenOddPrinter {
private boolean isEven;
private int index;
private int maxNumber;
public EvenOddPrinter(boolean isEven, int index, int maxNumber) {
super();
this.isEven = isEven;
this.index = index;
this.maxNumber = maxNumber;
}
public synchronized void printOdd () {
while(index < maxNumber) {
if(!isEven) {
System.out.println(index);
index++;
isEven = true;
notify();
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void printEven() {
while(index <= maxNumber) {
if(isEven) {
System.out.println(index);
index++;
isEven = false;
notify();
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
有人可以幫我解決這個問題嗎?
打印最后一個偶數后,偶數線程釋放鎖。 奇數線程退出該方法而不通知偶數線程。 從而陷入僵局。
public synchronized void printEven() {
while(index <= maxNumber) {
...
}
notify(); // add notify here
}
public synchronized void printOdd() {
while(index <= maxNumber) {
...
}
notify(); // add notify here
}
當奇數結束時,它永遠不會通知偶數線程。 所以這樣做。
public synchronized void printOdd () {
while(index < maxNumber) {
if(!isEven) {
System.out.println(index);
index++;
isEven = true;
notify();
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
notify(); // add a notify here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.