我写了下面的程序打印偶数和奇数:
public class PrintEvenOdd {
public static void main(String[] args) {
CurrentValue currentValue = new CurrentValue();
Thread oddThread = new Thread(new PrintOdd(10, currentValue));
Thread evenThread = new Thread(new PrintEven(10, currentValue));
oddThread.start();
evenThread.start();
}
}
class CurrentValue {
private int current = 0;
public int getCurrent() {
return current;
}
public void setCurrent(Integer current) {
this.current = current;
}
}
class PrintOdd implements Runnable {
private int noOfValuesToPrint;
private CurrentValue currentValue;
public PrintOdd(int noOfValuesToPrint, CurrentValue currentValue) {
this.noOfValuesToPrint = noOfValuesToPrint;
this.currentValue = currentValue;
}
public void run() {
while (true) {
synchronized (currentValue) {
System.out.println("Inside Print odd");
int current = currentValue.getCurrent();
System.out.println("Value of current in odd is " + current);
while (current % 2 != 0) {
try {
System.out.println("Value of current in odd is " + current + "and value of current % 2 is "
+ current % 2);
System.out.println("odd waiting");
currentValue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Odd no. is " + ++current);
currentValue.setCurrent(current);
currentValue.notify();
System.out.println("Notify executed from odd");
}
}
}
}
class PrintEven implements Runnable {
private int noOfValuesToPrint;
private CurrentValue currentValue;
public PrintEven(int noOfValuesToPrint, CurrentValue currentValue) {
this.noOfValuesToPrint = noOfValuesToPrint;
this.currentValue = currentValue;
}
public void run() {
while (true) {
synchronized (currentValue) {
System.out.println("Inside Print even");
int current = currentValue.getCurrent();
System.out.println("Value of current in even is " + current);
while (current % 2 == 0) {
try {
System.out.println("even waiting");
currentValue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Even no. is " + ++current);
currentValue.setCurrent(current);
currentValue.notify();
System.out.println("Notify executed from even");
}
}
}
}它给我的输出是:
内部打印奇数
奇数中电流的值为0
奇数号。是1
通知从奇数执行
内部打印奇数
奇数中电流的值为1
奇数中电流的值为1,电流%2值为1
奇数等待
内部打印甚至
电流的值为1
甚至没有。是2
通知从偶数执行
内部打印甚至
均匀电流的值为2
甚至等待
奇数中电流的值为1,电流%2值为1
奇数等待
我期望两个线程使用wait和notify机制轮流打印偶数和奇数。我做错了什么?我还尝试使current变量易失性,但它提供了相同的输出。
发布于 2020-07-25 05:49:48
在这种情况下,不更新while (current % 2 != 0) (和PrintEven中相反的)值。改用while (currentValue.getCurrent() % 2 != 0);去掉current变量或在循环中更新它。
https://stackoverflow.com/questions/63084467
复制相似问题