你能告诉我使用ScheduleThreadPoolExecutor的正确语法吗?

时间:2012-10-31 19:31:30

标签: java swing

为此;我希望“连续”按钮启动rollthedice(),然后“停止”按钮停止它,但是当我再次点击“连续”按钮时,我希望它再次启动rollthedice(),来回

scheduler = new ScheduledThreadPoolExecutor(1);

ScheduledFuture now = null;

Runnable runner = new Runnable(){
    public void run()
    {
        rollthedice();
    }
};


if(e.getSource()==continuous)
{

    now = scheduler.scheduleAtFixedRate(runner, 0, 500, TimeUnit.MILLISECONDS);
}
if(e.getSource()==stop)
{

    now.cancel(true);

}

1 个答案:

答案 0 :(得分:1)

您遗失的是此ScheduledFuture now

的作业
now = scheduler.scheduleAtFixedRate(runner, 0, 500,
                TimeUnit.MILLISECONDS);

然后你可以拨打now.cancel(true);

只需在类级别下方移动声明,即您可以移动到actionPerformed方法之上。之后它运作良好。

ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1);
ScheduledFuture<?> now = null;