我只是在探索 java.util.concurrent 包。
我了解到“ Future ”类有一个方法boolean cancel(boolean mayInterruptIfRunning)
请附上我写的测试代码:
package com.java.util.concurrent;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
public class FutureTester {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
int poolCnt = 1;
Callable<NumberPrinter> numberPrinter = null;
ScheduledThreadPoolExecutor schPool = new ScheduledThreadPoolExecutor(
poolCnt);
ScheduledFuture<NumberPrinter>[] numPrinterFutures = new ScheduledFuture[poolCnt];
FutureTask<NumberPrinter>[] futureTask = new FutureTask[poolCnt];
for (int i = 0; i < poolCnt; i++) {
numberPrinter = new NumberPrinter();
futureTask[i] = new FutureTask<NumberPrinter>(numberPrinter);
/*
* numPrinterFutures[i] = (ScheduledFuture<NumberPrinter>) schPool
* .schedule(futureTask[i], 0, TimeUnit.MILLISECONDS);
*/
numPrinterFutures[i] = (ScheduledFuture<NumberPrinter>) schPool
.submit(futureTask[i]);
}
//Thread.sleep(30);
if (numPrinterFutures.length > 0) {
System.out.println("Task completed ? "
+ numPrinterFutures[0].isDone());
System.out.println("Task cancelled ? "
+ numPrinterFutures[0].cancel(true));
System.out.println("Is task cancelled ? "
+ numPrinterFutures[0].isCancelled());
}
}
}
class NumberPrinter implements Callable<NumberPrinter> {
private int counter = 10;
@Override
public NumberPrinter call() throws Exception {
// TODO Auto-generated method stub
while (counter > 0) {
if (Thread.interrupted()) {/*OUCH !!!*/
return null;
}
System.out.println("counter = " + (counter--));
}
return this;
}
}
最初,我假设取消任务也会停止正在运行的线程的执行(不包括“OUCH”部分)。但我得到的输出如下:
counter = 10
Task completed ? false
counter = 9
Task cancelled ? true
counter = 8
Is task cancelled ? true
counter = 7
counter = 6
counter = 5
counter = 4
counter = 3
counter = 2
counter = 1
在进一步阅读stackoverflow本身时,据说
- 'cancel' 方法只能停止 'unstarted' 作业(与方法的 api 描述相矛盾)
- cancel 方法只是中断正在运行的线程,然后该线程必须从 run() 方法返回
因此,我包括了 'OUCH' 部分 - 一个 while 循环检查中断;输出如下:
Task completed ? false
counter = 10
Task cancelled ? true
Is task cancelled ? true
问题 :
如果应该编写类似于“OUCH”部分的内容来停止正在运行的线程,那么取消方法的实用程序/价值是什么。如果无法通过取消来停止线程,将 Callable 包装在 FutureTask 中有何帮助?我忽略的设计/概念/逻辑部分是什么?