【发布时间】:2019-10-13 11:59:00
【问题描述】:
有很多类似的问题,但没有对我有用的解决方案。
我有一个需要运行一段时间的 Callable。在执行 Call 方法期间,它必须定期在 while 条件中进行一些检查,以检查它是否必须继续运行。我还希望能够从外部停止可调用(API 调用)。
下面的代码是一个简化的版本,但它有同样的问题:
当 callable 返回时,线程保持在 WAITING 状态。我如何杀死这个线程?
public class MyCallable implements Callable<Foo> {
private AtomicBoolean stop = new AtomicBoolean(false);
@Override
public Foo call() {
System.out.printf("New thread with ID=%d\n",
Thread.currentThread().getId());
Foo foo = new Foo();
while (!stop.get()) {
try {
Thread.sleep(1000); // Sleep for some time before doing checks again
} catch (InterruptedException e) {
}
}
System.out.printf("State before returning foo: %s\n",
Thread.currentThread().getState());
return foo;
}
public void stop() {
this.stop.set(true);
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
MyCallable myCallable = new MyCallable();
ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
Future<Foo> future = executorService.submit(myCallable);
printThreads();
System.out.println("Calling stop\n");
myCallable.stop();
while (!future.isDone()) {
Thread.sleep(200);
}
System.out.println("After future is done: ");
printThreads();
}
// Helper method
private static void printThreads() {
List<Thread> threads = Thread.getAllStackTraces().keySet()
.stream()
.filter(t -> t.getName().contains("pool"))
.collect(Collectors.toList());
threads.forEach(t -> System.out.printf("ID=%s STATE=%s\t\n", t.getId(), t.getState()));
System.out.println();
}
}
这是程序的输出
【问题讨论】:
标签: java multithreading callable