如何通过使用jtogglebutton使用WatchService来停止用于查看文件夹的Java中的以下类型的线程[英] How to stop threads of following type in Java used for watching folders for files using WatchService for folders by using jToggleButton

问题描述

我想通过使用JToggleButton停止以以下方式生成的线程.这些线程用于观看文件夹.我尝试了很多,搜索了很多,但没有成功.任何身体都可以帮助并建议任何解决方案以停止产生的线程.即使在按下JToggleButton之后,这些线程在Netbeans中还活着. 我尝试了停止的挥发性条件, 仅供参考:我有一个用于启动和停止线程的JToggle按钮.

该代码是由NetBeans生成的,因此有一些额外的代码,但是您只能关注JtogGleactionListener内部的代码和另一类的代码:感谢您的帮助.

.

package threadnames;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level; 
import java.util.logging.Logger;
public class NewJFrame extends javax.swing.JFrame {

    public NewJFrame() {
        initComponents();
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jToggleButton1 = new javax.swing.JToggleButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jToggleButton1.setText("Stop");
    jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jToggleButton1ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(84, 84, 84)
            .addComponent(jToggleButton1)
            .addContainerGap(142, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(25, 25, 25)
            .addComponent(jToggleButton1)
            .addContainerGap(28, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                               
    ExecutorService exec = Executors.newCachedThreadPool();
    if (this.jToggleButton1.isSelected()) {
        try {
            // TODO add your handling code here:
            Path home = Paths.get(System.getProperty("user.dir"));
            WatchService watcher;

            watcher = home.getFileSystem().newWatchService();

                home.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
            Runnable task = new FileWatch(watcher);
            exec.submit(task);
            boolean terminated;
            terminated = exec.awaitTermination(1, TimeUnit.SECONDS);

            if (terminated) {
                System.out.println("All tasks completed.");
            } else {
                System.out.println("Some tasks are still running.");
            }
        } catch (IOException | InterruptedException ex) {
            Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        exec.shutdownNow();
    }
}                                              

public static void main(String args[]) {
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info    javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;


            }
        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException |        javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class
                .getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new NewJFrame().setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
public javax.swing.JToggleButton jToggleButton1;
// End of variables declaration                   
}

这是Run()的另一个类:

package threadnames;

import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.Watchable;

final class FileWatch implements Runnable {

private final WatchService watcher;

FileWatch(WatchService watcher) {
    this.watcher = watcher;
}

@Override
public void run() {
    while (!Thread.currentThread().isInterrupted()) {
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
            break;
        }
        Watchable dir = key.watchable();
        System.out.println(dir);
        for (WatchEvent<?> evt : key.pollEvents()) {
            System.out.println("   " + evt.context());
        }
    }
}
}

推荐答案

使用线程中断状态

使用线程的中断状态终止循环.这比您创建自己的标志要好,因为它可以使您的任务使用ExecutorService>使用;您可以通过提交时收到的Future取消特定任务,也可以用shutdownNow().

中断所有任务

除非您的任务在您创建和管理自己的线程中运行,否则在检测到中断后重新掌握中断状态是最安全的,以便您的呼叫者也可以处理它.换句话说,所有线程和任务都需要具有定义的中断策略并相应使用.

示例

这是一个示例Runnable使用 WatchService :

final class FileWatch implements Runnable {
  private final WatchService watcher;
  FileWatch(WatchService watcher) { this.watcher = watcher; }
  @Override
  public void run()
  {
    while (!Thread.currentThread().isInterrupted()) {
      WatchKey key;
      try {
        key = watcher.take();
      }
      catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
        break;
      }
      Watchable dir = key.watchable();
      System.out.println(dir);
      for (WatchEvent<?> evt : key.pollEvents()) {
        System.out.println("   " + evt.context());
      }
    }
  }
}

这是您可以使用此类服务​​的方法:

public static void main(String... argv)
  throws Exception
{
  Path home = Paths.get(System.getProperty("user.home"));
  WatchService watcher = home.getFileSystem().newWatchService();
  home.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.OVERFLOW);
  Runnable task = new FileWatch(watcher);
  ExecutorService exec = Executors.newCachedThreadPool();
  exec.submit(task);
  Thread.sleep(3000);
  exec.shutdownNow();
  boolean terminated = exec.awaitTermination(1, TimeUnit.SECONDS);
  if (terminated)
    System.out.println("All tasks completed.");
  else
    System.out.println("Some tasks are still running.");
}

由于FileWatch任务正确支持中断,因此您会看到此测试显示所有任务都在调用shutdownNow()之后不久完成.如果将使用其他终止方法的任务添加到ExecutorService中,您将看到它们继续运行.

有关代码

目前的代码存在两个问题.这是对jToggleButton1ActionPerformed()事件处理程序的分析,当按下按钮时,由Swing Event Dispatch线程( edt )调用.

When the button is pressed,
  create a new ExecutorService as a local variable.
  If toggle selected,
    submit a file watching task to the executor, and
    block the EDT for 1 second, or until the executor is shutdown.
  Otherwise,
    shutdown the newly-created executor.
  Discard reference to the executor.

第一个问题是,由于执行程序服务除了局部变量以外的任何地方都不会存储,因此一旦该方法退出,对该特定实例的引用将永远丢失,并且无法在其上调用shutdownNow().

第二个问题是,如果真正想要阻止EDT(可能不是一个好主意),直到遗嘱执行人终止,则在调用shutdownNow()>(在您的" else"子句中,何时未选择切换时),则应执行此操作,提交任务后不是.再次查看上面的示例,您会看到我只在关闭遗嘱执行人后才等待终止.

从该方法中提升了执行人员服务变量,并使其成为类的成员变量.这将允许切换按钮处理程序访问ExecutorService的同一实例并将其关闭.然后,将等待终止的等待移至未选择的切换分支.

这就是流程:

When the button is pressed,
  If toggle selected,
    create a new executor service and assign it to a member variable, and
    submit a file watching task to the service.
  Otherwise,
    shutdown the executor, and
    wait for the service to terminate.

另外,在这里使用,newSingleThreadedExecutor()就足够了.

其他推荐答案

一种方法是使用stop将A volatile boolean设置为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();
    }
  }
}

如果线程可能被阻塞,您可以安排中断它,但是当然,这当然不能保证该线程可能不会被阻止,只是忙.

.

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();
    }
  }
}

如果使用 watchService.take().

如果大多数IO进程忙于

,它也应中断线程.

其他推荐答案

有一个Thread.stop()方法,但是已经弃用,因为它不安全.

您可以修改一些变量,以指示目标线程应停止运行.

本文地址:https://www.itbaoku.cn/post/978540.html