Reputation: 1301
I am new in Java multithreading, i just implemented Timer class to execute method on specific interval time.
here my code :
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");
}
}
but the output like this :
finish
inside timer
I want it like this :
inside timer
finish
so how to wait timer thread to complete and then continue execute code in main thread? any suggestion?
Upvotes: 1
Views: 2529
Reputation: 347194
Your question is somewhat vague and may be better answered via Java's Concurrency Tutorial, however...
Use a "monitor lock"
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();
}
}
}
Use a 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();
}
}
Use a callback or simply call a method from the Timer
class
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();
}
}
Upvotes: 7