How to stop a java code from running using a stop button

前端 未结 2 748
被撕碎了的回忆
被撕碎了的回忆 2021-02-05 21:45

I have a button that calls a method from the backing Bean. This method allows to extract data from parsing html code. While the method is running i have a dialog showing a progr

2条回答
  •  故里飘歌
    2021-02-05 22:00

    ExecutorService with interrupt friendly tasks

    ExecutorService documentation


    • Instead of directly calling the method, convert the method into an ExecutorService's task.

      public class SearchEmailsTask implements Runnable {
      
          private EmailSearcher emailSearcher;
      
          public SearchEmailsTask(EmailSearcher emailSearcher) {
              this.emailSearcher = emailSearcher;
          }
      
          @Override
          public void run() {
              emailSearcher.searchEmails();
          }
      }
      

      You can use Callable if you want to return something.


      • When you want call the method, submit that task to an ExecutorService.

        ExecutorService executorService = Executors.newFixedThreadPool(4);
        
        SearchEmailsTask searchEmailsTask = new SearchEmailsTask(new EmailSearcher());
        
        Future future = executorService.submit(searchEmailsTask);
        

      • Keep a reference to the task.

        private static Map > results = new HashMap >();
        

        A map should be a good idea to store multiple Future objects. You can of course go for something better if you want.


      • Call cancel on the task whenever required.

        future.cancel(true);
        

      Note:
      Task should have suitable checks for thread interruption for proper cancellation.
      To achieve this, refer to

      1. Future task of ExecutorService not truly cancelling
      2. how to suspend thread using thread's id?

      Good luck.

      提交回复
      热议问题