下面是一个示例程序。如果我取消注释 Thread.sleep 它工作正常。但是可能有一些需要,我们不确定在 Call 方法中编写的代码需要多少时间,可能是无限的时间。或者,可能是一个糟糕的程序,其中 Call 方法中的数据库连接逻辑需要更多时间,我们需要终止。
您能否告诉我,如果我评论 thread.sleep 以及如何在不编写 Thread.interrupted 条件的情况下杀死和停止它,为什么下面的代码不起作用。(假设我没有权限在 Call 方法中写入任何逻辑)
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class stopThreadTest {
public static void main(String[] args) {
java.util.concurrent.ExecutorService executor = null;
Future a1 = null;
try {
executor = java.util.concurrent.Executors.newFixedThreadPool(4);
a1 = executor.submit(new java.util.concurrent.Callable() {
public String call() throws Exception {
int i = 0;
while (true) {
//Thread.sleep(100);
// System.out.println("hello");
if (i > 10)
break;
}
return null;
}
});
// Wait until all threads are finish
/*
* while (!executor.isTerminated()) { }
*/
System.out.println("Calling PartialOrFullSuccessCheck");
try {
boolean isThreadError = (a1 != null) ? ((a1.get(2,
TimeUnit.SECONDS) == null) ? false : true) : false;
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// interrupts the worker thread if necessary
System.out
.println("Cancelled" + a1.isDone() + a1.isCancelled());
a1.cancel(true);
System.out.println("encountered problem while doing some work");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// interrupts the worker thread if necessary
System.out
.println("Cancelled" + a1.isDone() + a1.isCancelled());
a1.cancel(true);
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// interrupts the worker thread if necessary
System.out
.println("Cancelled" + a1.isDone() + a1.isCancelled());
a1.cancel(true);
}
} finally {
System.out.println("ShutDown Executor");
executor.shutdown();
}
}
}