[英]Printing even and odd number using two threads
我写了下面的程序来打印偶数和奇数:
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");
}
}
}
}
它给我的 Output 是:
内印奇数
奇数电流值为0
奇数是 1
通知从奇数执行
内印奇数
奇数电流值为 1
奇数电流值为 1,电流 %2 值为 1
奇怪的等待
内部打印甚至
偶数中的电流值为1
甚至没有。 是 2
通知从偶数执行
内部打印甚至
偶数中的电流值为2
甚至等待
奇数电流值为 1,电流 %2 值为 1
奇怪的等待
我期望两个线程使用wait
和notify
机制轮流打印偶数和奇数。 我究竟做错了什么? 我也尝试过使current
变量易失,但它给出了相同的 output。
在这种情况下while (current % 2 != 0)
(和PrintEven
中的相反值)时, current
的值不会更新。 使用while (currentValue.getCurrent() % 2 != 0)
代替; 摆脱current
变量或在循环中更新它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.