Java等待Timer线程完成

时间:2018-07-13 03:42:08

标签: 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");
    }

}

但是这样的输出:

finish
inside timer

我想要这样:

inside timer
finish

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

1 个答案:

答案 0 :(得分:4)

您的问题有些含糊,可以通过Java's 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();
    }

}