Java一次性定时器终止主要功能

时间:2013-09-20 10:15:01

标签: java timer

我用Observer模式实现了一个简单的计时器。我希望在运行5分钟后终止主函数。基本上我需要的是简单的一次性超时功能。我怎样才能做到这一点?我的代码不起作用。下面是计时器类

public class OneShotTimer  extends Observable implements Runnable{

@Override
public void run() {
    // TODO Auto-generated method stub
    try {
        Thread.sleep(30);
    } catch (Exception e) {
        // TODO: handle exception
        System.out.println("Exception in timer");
    }
    notifyObservers();
}

在main类的构造函数中,我初始化该计时器。

public GreenOverlayMain(){
    timer = new OneShotTimer();
    timer.addObserver(this);
    Thread t = new Thread(timer, "mythread");
    t.start();
}

然而,从不执行主类的update()函数,因为超时永远不会发生。 MainClass实现Observer接口。以下是更新功能。

@Override
public void update(Observable o, Object arg) {
    // TODO Auto-generated method stub
    System.gc();
    System.exit(0);
}

1 个答案:

答案 0 :(得分:3)

此示例打印update结束执行。

public static void main(String[] args){
    //scheduler executor is a lot more sophisticated solution
    final ScheduledExecutorService sheduler = Executors.newScheduledThreadPool(1);
    class MyO extends Observable {
        public void trackChanged(){
            setChanged(); //this method is protected in super class
        }
    };
    //must be final because it used in nested class
    final MyO o = new MyO();
    o.addObserver(new Observer() {
        @Override
        public void update(Observable o, Object arg) {
            //your processing here
            System.out.println("update");
            sheduler.shutdown();
        }
    });
    sheduler.schedule(new Runnable() {
        @Override
        public void run() {
            o.trackChanged();
            o.notifyObservers();
        }
    }, 3, TimeUnit.SECONDS); //set any timout
}