1

我用观察者模式实现了一个简单的计时器。我想在 main 函数运行 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();
}

在主类的构造函数中,我初始化了那个计时器。

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

2 回答 2

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
}
于 2013-09-20T10:55:14.053 回答
0

这是一个可重复使用的 OneShotTimer。

    new OneShotTimer(3, () -> setChange());
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class OneShotTimer
{

    final ScheduledExecutorService sheduler = Executors.newScheduledThreadPool(1);

    /// Call [callback] after [duration] seconds.
    public OneShotTimer(int duration, OneShotCallback callback)
    {
        sheduler.schedule(() -> _callback(callback), duration, TimeUnit.SECONDS);
    }

    void _callback(OneShotCallback callback)
    {
        sheduler.shutdown();
        callback.callback();
    }

    public interface OneShotCallback
    {
        void callback();
    }

}

于 2022-02-10T02:33:28.770 回答