[英]Java wait for Timer thread to complete
我是Java多線程技術的新手,我只是實現了Timer類,以在特定的間隔時間執行方法。
這是我的代碼:
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new MyTimerTask(), 3000);
//execute this code after timer finished
System.out.println("finish");
}
private static class MyTimerTask extends TimerTask {
@Override
public void run() {
System.out.println("inside timer");
}
}
但輸出是這樣的:
finish
inside timer
我想要這樣:
inside timer
finish
那么如何等待計時器線程完成,然后繼續在主線程中執行代碼? 有什么建議嗎?
您的問題有些含糊,可以通過Java的Concurrency Tutorial更好地回答,但是...
使用“顯示器鎖”
public static void main(String[] args) {
Object lock = new Object();
Timer timer = new Timer();
timer.schedule(new MyTimerTask(lock), 3000);
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException ex) {
}
}
//execute this code after timer finished
System.out.println("finish");
}
private static class MyTimerTask extends TimerTask {
private Object lock;
public MyTimerTask(Object lock) {
this.lock = lock;
}
@Override
public void run() {
System.out.println("inside timer");
synchronized (lock) {
lock.notifyAll();
}
}
}
使用CountDownLatch
...
public static void main(String[] args) {
CountDownLatch cdl = new CountDownLatch(1);
Timer timer = new Timer();
timer.schedule(new MyTimerTask(cdl), 3000);
try {
cdl.await();
} catch (InterruptedException ex) {
}
//execute this code after timer finished
System.out.println("finish");
}
private static class MyTimerTask extends TimerTask {
private CountDownLatch latch;
public MyTimerTask(CountDownLatch lock) {
this.latch = lock;
}
@Override
public void run() {
System.out.println("inside timer");
latch.countDown();
}
}
使用回調或僅從Timer
類調用方法
public static void main(String[] args) {
CountDownLatch cdl = new CountDownLatch(1);
Timer timer = new Timer();
timer.schedule(new MyTimerTask(new TimerDone() {
@Override
public void timerDone() {
//execute this code after timer finished
System.out.println("finish");
}
}), 3000);
}
public static interface TimerDone {
public void timerDone();
}
private static class MyTimerTask extends TimerTask {
private TimerDone done;
public MyTimerTask(TimerDone done) {
this.done = done;
}
@Override
public void run() {
System.out.println("inside timer");
done.timerDone();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.