How to stop threads of following type in Java used for watching folders for files using WatchService for folders by using jToggleButton

后端 未结 4 651
日久生厌
日久生厌 2021-01-17 03:14

I would like to stop threads generated in the following manner by using jToggleButton. The threads are used for watching folders for files. I tried a lot, and searched alot,

4条回答
  •  無奈伤痛
    2021-01-17 03:54

    One way would be to use a stop method that sets a volatile boolean to true.

    public class HelloRunnable implements Runnable {
      private volatile boolean stop = false;
    
      public void run() {
        if (!stop) {
          System.out.println("Hello from a thread!");
        }
      }
    
      public void stop() {
        stop = true;
      }
    
      public static void main(String args[]) {
        for (int i = 0; i < 5; i++) {
          HelloRunnable hr = new HelloRunnable();
          new Thread(hr).start();
          hr.stop();
        }
      }
    }
    

    If the thread might be blocked you can arrange to interrupt it but of course this is not guaranteed to interrupt the thread as it may not be blocked, just busy.

    public class HelloRunnable implements Runnable {
      private volatile boolean stop = false;
      private volatile Thread thread = null;
    
      public void run() {
        thread = Thread.currentThread();
        if (!stop) {
          System.out.println("Hello from a thread!");
        }
      }
    
      public void stop() {
        stop = true;
        if ( thread != null ) {
          thread.interrupt();
        }
      }
    
      public static void main(String args[]) {
        for (int i = 0; i < 5; i++) {
          HelloRunnable hr = new HelloRunnable();
          new Thread(hr).start();
          hr.stop();
        }
      }
    }
    

    This last technique should also work if using WatchService.poll(...) or WatchService.take().

    It should also interrupt the thread if it is busy with most IO processes.

提交回复
热议问题