Java等待定时器线程完成

Gus*_*rya 0 java multithreading

我是 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");
    }

}
Run Code Online (Sandbox Code Playgroud)

但输出是这样的:

finish
inside timer
Run Code Online (Sandbox Code Playgroud)

我想要这样:

inside timer
finish
Run Code Online (Sandbox Code Playgroud)

那么如何等待定时器线程完成,然后在主线程中继续执行代码呢?有什么建议吗?

Mad*_*mer 6

您的问题有些含糊,可以通过Java 的并发教程更好地回答,但是...

你可以...

使用“监视器锁”

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();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

你可以...

使用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();
    }

}
Run Code Online (Sandbox Code Playgroud)

你可以...

使用回调或简单地从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();
    }

}
Run Code Online (Sandbox Code Playgroud)