Search code examples
javasingle-threaded

Single thread with a delay to start


What im trying to do is : Pressing one button change simple value. If value remains unchanged for 3 sec, i wanna execute my method. So i need a single thread which would start(and kill all others) on every button click. I know

Executor executor = Executors.newSingleThreadScheduledExecutor();

but it can't have a delay. What would be the best practice to do this ?


Solution

  • Either you can go with simple Thread start-stop/interrupt thing or you can use API's like ScheduledExecutorService.
    An example of how to do with ScheduledExecutorService is below

    //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.