简体   繁体   中英

Stopping ScheduledExecutorService when button action is performed in the UI

I have created a scheduledExecutorService as below

ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable() {
  @Override
  public void run() {
    // do stuff
  }
}, 0, 5, TimeUnit.SECONDS);

I would like to stop service when stop button is clicked in the UI or JSP . Any help on this is so much appreciated

ScheduledFuture::cancel

When calling ScheduledExecutorService::scheduleAtFixedRate , you get back a ScheduledFuture . Currently your code ignores that returned object, and drops it.

Change your code to capture that scheduled future object.

ScheduledFuture future = exec.scheduleAtFixedRate(… 

The ScheduledFuture has methods to cancel the task, and to ask if the task is already cancelled .

Take a look at shutdownNow() method of the executor.

exec.shutdownNow();
exec.awaitTermination();

It does almost what you want. It does not stop the thread immediately (cause it's not safe). Instead it sets isInterrupted() flag notifying the running thread that is should stop. So, your Runnable has to check for that flag from time to time. And when it finds the flag is set, it should return from the run() method.

exec.awaitTermination(); is waiting until the thread is stopped. After that line you may be sure that the thread has stopped execution.

Create a class with a flag variable. Check the value of that flag and stop the thread if needed.

public class MyRunnable implements Runnable {
   private AtomicBoolean running = new AtomicBoolean(true);

   public void run() {
       while (running.get()) {
          ...
       }
   }

   public void stopMe() {
      running.set(false);
   }
} 


ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
MyRunnable myRunnable = new MyRunnable();
exec.scheduleAtFixedRate(myRunnable, 0, 5, TimeUnit.SECONDS);

...
myRunnable.stopMe();

Note: use an AtomicBoolean so you are sure to not have a side effect setting and checking the value of running variable in a multithread environment:

A boolean value that may be updated atomically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM