0

我以前看过这样的帖子,但问题或答案不清楚,如果你以前听过,请多多包涵。我有一个计时器,我希望在计时器关闭时发生一个 ActionEvent。我不想使用 javax.swing.Timer 方法。如何才能做到这一点?没有必要解释,但这会有所帮助。我正在寻找类似 ActionEvent.do()方法的东西

我的代码:

/**
 * 
 * @param millisec time in milliseconds
 * @param ae action to occur when time is complete
 */
public BasicTimer(int millisec, ActionEvent ae){
    this.millisec = millisec;
    this.ae = ae;
}

public void start(){
    millisec += System.currentTimeMillis();
    do{
        current = System.currentTimeMillis();
    }while(current < millisec);

}

谢谢!丹多18

4

1 回答 1

0

在这里,您有一些简单的计时器实现。为什么你只是不检查其他计时器是如何工作的?

 public class AnotherTimerImpl {

        long milisecondsInterval;
        private ActionListener listener;
        private boolean shouldRun = true;

        private final Object sync = new Object();

        public AnotherTimerImpl(long interval, ActionListener listener) {
            milisecondsInterval = interval;
            this.listener = listener;
        }

        public void start() {
            setShouldRun(true);
            ExecutorService executor = Executors.newSingleThreadExecutor();
            executor.execute(new Runnable() {

                @Override
                public void run() {
                    while (isShouldRun()) {
                        listener.actionPerformed(null);
                        try {
                            Thread.sleep(milisecondsInterval);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            break;
                        }
                    }

                }
            });
        }

        public void stop() {
            setShouldRun(false);
        }

        public boolean isShouldRun() {
            synchronized (sync) {
                return shouldRun;
            }
        }

        public void setShouldRun(boolean shouldRun) {
            synchronized (sync) {
                this.shouldRun = shouldRun;
            }
        }

    }
于 2013-12-22T08:36:11.607 回答