如何取消正在运行的任务并将其替换为一个新的,在同一个线程? [英] How do I cancel a running task and replace it with a new one, on the same thread?

查看:217
本文介绍了如何取消正在运行的任务并将其替换为一个新的,在同一个线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在下面的代码中,我使用了一个

单线程执行程序来启动新任务并捕获代表它的 Future 。然后我使用 Future 取消任务。


  1. 为什么我的代码无效?

  2. 如何取消正在运行的任务并将其替换为同一个线程上的新任务?

示例代码:

  import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

类任务实现Runnable {
public void run(){
System.out.println(New task started);
int i = 0; while(true)i ++;
}
}

public class TaskLauncher extends JFrame {
private JButton button = new JButton(Start new task);
private ExecutorService executor = Executors.newSingleThreadExecutor();
private Future<?>未来;

public TaskLauncher(){
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
if(future!= null)future .cancel(true);
future = executor.submit(new Task());
}
});

add(button);

pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}

public static void main(String [] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new TaskLauncher();
}
});
}
}


解决方案

调用cancel对Future对象不会导致任务停止。有关详细信息,请参阅API文档。此外,请检查此 SO问题,其中显示了您必须如何编码



修改您的任务,如下所示:

  class Task实现Runnable {
public void run(){
System.out.println(New task started);
int i = 0;
while(true){
i ++;
if(Thread.currentThread()。isInterrupted()){
System.out.println(Gracefully);
return;
}
}
}
}


I would like to cancel a running task and replace it with a new one, on the same thread.

In the code below, I used a single-thread executor to start a new task and capture a Future representing it. I then used the Future to cancel the task. However, the task did not cancel.

  1. Why does my code not work?
  2. How do I cancel a running task and replace it with a new one, on the same thread?

Example code:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

class Task implements Runnable {
    public void run() {
        System.out.println("New task started");
        int i = 0; while (true) i++;
    }
}

public class TaskLauncher extends JFrame {
    private JButton button = new JButton("Start new task");
    private ExecutorService executor = Executors.newSingleThreadExecutor();
    private Future<?> future;

    public TaskLauncher() {
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                if (future != null) future.cancel(true);
                future = executor.submit(new Task());
            }
        });

        add(button);

        pack();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TaskLauncher();
            }
        });
    }
}

解决方案

Just calling cancel on the Future object will not cause the task to stop. See the API docs for more information. Also check this SO Question which shows how you have to code your task so that it can be cancelled using the Future object.

Modify your task like this:

class Task implements Runnable {
    public void run() {
        System.out.println("New task started");
        int i = 0; 
        while (true) {
            i++;
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("Exiting gracefully");
                return;
            }
        }
    }
}

这篇关于如何取消正在运行的任务并将其替换为一个新的,在同一个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆