我是Java编程新手。我想用wait()和notify()来运行两个线程。但我不能使用线程同步,睡眠,良率或等待(参数)任务标志。我写了它,但我不得不使用睡眠。有人可以帮助我改变它没有睡眠。 这是我的主类Java - 两个线程wait()和notify()
public class mainClass{
public static void main(String args[]) throws InterruptedException {
final Processor processor = new Processor();
for(int i=0; i<100; i++){
final int z = i;
Thread trainer = new Thread(new Runnable(){
public void run(){
try{
processor.produce(z);
}catch(InterruptedException e){
e.printStackTrace();
}
}
});
Thread sportsman = new Thread(new Runnable(){
public void run(){
try{
processor.consume(z);
}catch(InterruptedException e){
e.printStackTrace();
}
}
});
trainer.start();
sportsman.start();
trainer.join();
sportsman.join();
}
System.out.println("100 Tasks are Finished.");
}
}
这是我的第二个类。
public class Processor {
public void produce(int n) throws InterruptedException {
synchronized (this){
System.out.println("Trainer making " + (n+1) + " Task...");
wait();
System.out.println("");
}
}
public void consume(int m) throws InterruptedException {
Thread.sleep(1);
//I want to run the code without using sleep and get same output
synchronized (this){
System.out.println("Sportman doing " + (m+1) + " Task...");
notify();
}
}
}
这是我的输出。
Trainer making 1 Task...
Sportman doing 1 Task...
Trainer making 2 Task...
Sportman doing 2 Task...
.
.
.
Trainer making 99 Task...
Sportman doing 99 Task...
Trainer making 100 Task...
Sportman doing 100 Task...
100 Tasks are Finished.
谢谢。我的英语不好。对不起。
如果您没有等待的线程通知它会丢失。在进行状态更改后需要通知,那么您需要在wait()的循环中检查状态更改,因为它可能会虚假地唤醒。 –
这里记录了正确使用'wait()'和'notify()'。 https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html –
你想要/期望输出看起来像什么? –