单线程有延迟启动

时间:2015-06-04 10:45:32

标签: java single-threaded

我想要做的是:按一个按钮改变简单值。如果值保持3秒不变,我想执行我的方法。所以我需要一个单独的线程,它会在每次点击按钮时启动(并杀死所有其他线程)。我知道

Executor executor = Executors.newSingleThreadScheduledExecutor();

但它不会有延迟。这样做的最佳做法是什么?

2 个答案:

答案 0 :(得分:1)

您可以简单地使用旧的Thread类或Runnable接口:单击按钮后立即启动线程,执行Thread.sleep(3000)作为第一条指令,然后检查值是否为没有改变。 在开始线程之前,检查另一个线程是否已经存在,如果有,请在其上调用interrupt()并处理InterruptedException以正常终止它。

如果您想使用较新的并发API,请注意Executors.newSingleThreadScheduledExecutor()返回ScheduledExecutorService(不是简单的Executor)并且它允许启动具有延迟的线程,顾名思义。查看Javadoc

答案 1 :(得分:0)

您可以使用简单的Thread启停/中断功能,也可以使用ScheduledExecutorService之类的API。 如何使用ScheduledExecutorService的示例位于

之下
//Start as many threads as you want upon button click... (since you said i want to kill all other threads, so i assume you want to start some threads soon upon button click)
            ScheduledExecutorService service = Executors.newScheduledThreadPool(3);
            service.schedule(new Thread(), 0, TimeUnit.SECONDS);
            service.schedule(new Thread(), 0, TimeUnit.SECONDS);
            service.schedule(new Thread(), 0, TimeUnit.SECONDS);

            //Start single thread after 3 seconds.
            ScheduledExecutorService serviceCheck = Executors.newScheduledThreadPool(3);
            serviceCheck.schedule(new Thread(), 3, TimeUnit.SECONDS);
            //In this thread created using "serviceCheck", check with value has not changed then use `service.shutdownNow();` to shutdown all previously started threads and then do whatever you want.