62,614
社区成员
发帖
与我相关
我的任务
分享
import java.util.Timer;
import java.util.TimerTask;
public class Test1 {
public static void main(String[] args) {
final MyTimerTask task = new MyTimerTask();
new Timer().scheduleAtFixedRate(task, 0, 1000);
Thread thread = new Thread() {
public void run() {
while(true) {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (task) {
task.condition = true;
System.out.println("notify...");
task.notifyAll();
}
}
};
};
thread.start();
}
}
class MyTimerTask extends TimerTask{
public volatile boolean condition = false;
public void run() {
synchronized (this) {
while(!condition) {
System.out.println("Waiting...");
try {
wait();
} catch (InterruptedException e) {
Thread.interrupted();
}
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Continue task...Done.");
condition = false;
}
}
synchronized (task) {
task.condition = true;
System.out.println("notify...");
task.notifyAll();
}