我开始使用2个线程,一个用于奇数,另一个用于偶数,但运行结果是我得到的两倍"请输入x";。我的问题,如何显示";请输入x〃;只有一次,仍然使用两个线程?
@Override
public void run() {
System.out.println("Please input x:");
x= input.nextInt();
System.out.println("Please input y:");
y=input.nextInt();
while (x< y) {
synchronized (lock) {
while (x % 2 != remainder) { // wait for numbers other than remainder
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + " " + x);
x++;
lock.notifyAll();
}
}
}
以下是您需要做的事情的大致情况。
首先,修改TaskEvenOdd
,以便将x
和y
值传递给其构造函数,并将它们存储在实例变量中:
public class TaskEvenOdd implements Runnable {
private int remainder;
private int x;
private int y;
public TaskEvenOdd(int remainder, int x, int y){
this.remainder = remainder;
this.x = x;
this.y = y;
}
@Override
public void run() {
while (x < y) {
/// etc...
}
}
主要是,提示输入x
和y
值,并将它们作为参数传递给OddEvenTask
构造函数:
public static void main(String[] args){
System.out.println("Enter x:");
int x = input.nextInt();
System.out.println("Enter y:");
int y = input.nextInt();
OddEvenTask oddTask = new OddEvenTask(1, x, y);
OddEvenTask evenTask = new OddEvenTask(0, x, y);
// Now create and start your threads
}