我遇到了需要停止运行 Executor 服务线程的情况。
我已经阅读了其他帖子中的解决方案,其中提到使用 Future 对象并取消任务。
但我宁愿尝试不同的方法。
如果这种方法有任何问题,谁能告诉我。
以下是我的 Runnable 类。
public class TestRunnable implements Runnable {
Thread t;
@Override
public void run() {
// TODO Auto-generated method stub
setT(Thread.currentThread());
while(true)
{
if(Thread.currentThread().isInterrupted())
{
System.out.println("From Inside thread, Exiting");
System.exit(0);
}
}
}
public void setT(Thread t) {
this.t = t;
}
public Thread getT() {
return t;
}
}
以下是我的主要方法:
import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ruunTest {
public static void main(String[] args) throws IOException, InterruptedException {
// TODO Auto-generated method stub
ExecutorService service = Executors.newCachedThreadPool();
TestRunnable test = new TestRunnable();
service.execute(test);
Thread.sleep(1000);
System.out.println("About to Interrupt");
test.getT().interrupt();
}
}
最佳答案
唯一正确的做法是取消
你的任务对应的Future
,在你的任务中,你应该定期检查线程是否被中断.
类似的东西:
public class Task implements Callable<Void> {
@Override
public Void call() throws InterruptedException {
while(true) {
// Check regularly in your code if the thread has been
// interrupted and if so throws an exception to stop
// the task immediately
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException("Thread interrupted");
}
}
}
}
那么你的主要代码是:
ExecutorService service = Executors.newCachedThreadPool();
// My task
Task task = new Task();
// Submit the task and get the corresponding future
Future<?> future = service.submit(task);
...
// Cancel the task which will interrupt the thread that was executing the
// task if any
future.cancel(true);
关于java - 停止执行程序服务中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37983867/