【发布时间】:2016-07-27 12:14:54
【问题描述】:
我有两个线程 t0 和 t1,它们分别在下面的代码部分 Run_0 和 Run1 中发布。我想要做的是,当 t0 正在写入或执行持续 7 秒的任务时,t1 应该等待。当 7 秒过去,应通知 t1 继续工作。我尝试使用 wait() 和 notify() 来做到这一点,但在运行时我希望 t0 启动但控制台只显示“T1 正在工作”并且 t0 没有打印任何内容,就好像它没有打印一样 开始
请告诉我为什么会发生这种行为。
代码:
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:qat.com/using-waitnotify-instead-thread-sleep-java
标签: java android multithreading runnable