我有两个线程t0和t1,分别在代码段Run_0和Run1中列出了runnables。我想要做的是,当t0正在写或执行持续7秒的任务时,t1应该在等待。当经过7秒时,应该通知t1继续工作。我尝试使用wait()和notify(),但在运行时我期望t0启动,但控制台只显示“T1正在工作”,t0不打印任何东西,就好像它不是 开始wait()不强制线程等待?
请让我知道为什么会发生这种行为。
代码:
public static void main(String[] args) {
t0 = new Thread(new Run_0());
t1 = new Thread(new Run_1());
t0.start();
t1.start();
}
private static class Run_0 implements Runnable {
public void run() {
// TODO Auto-generated method stub
while (true) {
long startTime = TimeUtils.getTSSec();
synchronized (t1) {
try {
t1.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("T0 is writing");
//simulate doing some work
while((TimeUtils.getTSSec()-startTime) <= 7) {
}
System.out.println("T0 finished writing");
synchronized (t1) {
t1.notify();
}
startTime = TimeUtils.getTSSec();
while((TimeUtils.getTSSec()-startTime) <= 7) {
}
}
}
}
private static class Run_1 implements Runnable {
public void run() {
// TODO Auto-generated method stub
while(true) {
System.out.println("T1 is working");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
也许你应该先看看如何在这里首先使用'wait'和'notify':http://www.qat.com/using-waitnotify-instead-thread-sleep-java/ – nidomiro
或者在这里,https ://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html –