简体   繁体   English

如何停止工作ScheduledExecutorService?

[英]How to stop working ScheduledExecutorService?

In my project I have a chart which can turn into an animation depending on if we click Start or Stop button. 在我的项目中,有一个图表可以变成动画,具体取决于我们单击“开始”还是“停止”按钮。 I can make it start, but I don't know how to stop it. 我可以启动它,但是我不知道如何停止它。 Method shutdownNow() gives no result. 方法shutdownNow()没有给出结果。 How can I do this? 我怎样才能做到这一点? Here is my code 这是我的代码

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

}

As per java docs how shutdownNow() works like below. 根据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. 例如,典型的实现将通过{@link Thread#interrupt}取消,因此任何无法响应中断的任务都可能永远不会终止。

So, it will set interrupted flag true, so you need to correctly manage the InterruptedException and / or explicitly check Thread.currentThread().isInterrupted() . 因此,它将中断标志设置为true,因此您需要正确管理InterruptedException和/或显式检查Thread.currentThread().isInterrupted() You can use below code to stop your current running inputted thread. 您可以使用以下代码停止当前正在运行的输入线程。

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

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

but personally i would: 但我个人会:

  • extract runner in method 方法中提取流道
  • stop runner by flipping a boolean 通过翻转布尔值来停止跑步
  • call scheduler.shutdownNow(); 调用scheduler.shutdownNow(); when needed (on close JPanel?) 需要时(在关闭的JPanel上?)

example: 例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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