如何停止工作的 ScheduledExecutorService?

How to stop working ScheduledExecutorService?

在我的项目中,我有一个图表,它可以根据我们是单击“开始”还是“停止”按钮变成动画。我可以让它开始,但我不知道如何停止它。方法 shutdownNow() 没有给出任何结果。我怎样才能做到这一点?这是我的代码

public class Animation extends JPanel{
    // initializations
    ScheduledExecutorService scheduler = 
               Executors.newScheduledThreadPool(1);

    Animation(String s){
        // initialization of chart and adding XYSeries 
        this.add(chartPanel);   
    }

    public void go() {
        scheduler.scheduleAtFixedRate( (new Runnable() {

        @Override
        public void run() {
            double first;
            l = dataset.getSeries();

            while(true) {   
                first = (double)l.get(0).getY(0);
                for (int k = 0; k < l.get(0).getItemCount(); k++) {
                    if (k + 1 < l.get(0).getItemCount()) l.get(0).updateByIndex(k, l.get(0).getY(k+1));
                    else l.get(0).updateByIndex(k, first);
                }   
            }
            }

        }),  0, 5, MILLISECONDS);

    }

    public void stop() {
        scheduler.shutdownNow();
    }

}

根据 java 文档,shutdownNow() 的工作原理如下。

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via {@link Thread#interrupt}, so any a task that fails to respond to interrupts may never terminate.

因此,它会将中断标志设置为真,因此您需要正确管理 InterruptedException 和/或显式检查 Thread.currentThread().isInterrupted()。您可以使用以下代码停止当前 运行 输入的线程。

while (!Thread.currentThread().isInterrupted()) {
    // your code here           
}

(!Thread.currentThread().isInterrupted()) 可能是一个解决方案

但我个人会:

  • 在方法中提取转轮
  • 通过翻转布尔值停止跑步者
  • 需要时调用 scheduler.shutdownNow();(在关闭 JPanel 时?)

示例:

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
boolean running;

public void setup() {
   scheduler.scheduleAtFixedRate(runner(), 0, 5, TimeUnit.MILLISECONDS);

}

private Runnable runner() {
  return () -> {

    while (running) {
       try {
        //DO YOUR STUFF HERE
        System.err.println("RUNNING");
        Thread.sleep(500);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
   }
 };
}

public void go() {
  running = true;
}

public void stop() {
 running = false ;
}

public void shutdown() {
  scheduler.shutdownNow();
}


public static void main(String[] args) throws InterruptedException {
  Demo tasks = new Demo();
  tasks.setup();
  for (int i = 1; i <= 5; i++) {
    System.err.println("GO FOR IT " + i);
    tasks.go();
    Thread.sleep(2000);
    tasks.stop();
    Thread.sleep(1000);
  }
  tasks.shutdown();
}