【发布时间】:2017-07-03 11:13:52
【问题描述】:
我想取消提交给 ExecutorService 的任务,从而允许相应的线程从队列中选择一个新任务。
现在这个问题在这个论坛上已经回答了很多次了......就像检查Thread.currentThread().interrupt()或catch (InterruptedException e)一样。但是,如果控制流跨越多个方法,那么进行这些检查会使代码变得笨拙。因此,如果可能的话,请在 java 中提出一些优雅的方法来实现此功能。
我面临的问题是 future.cancel 实际上不会取消任务。相反,它只是将InterruptedException 发送给正在执行的任务,任务负责将自己标记为完成并释放线程。
所以我所做的是,每当在执行过程中的任何地方抛出异常时,我都必须放置下面的代码块,这显然看起来不太好!
if(e instanceof InterruptedException) {
throw e;
}
那么,如何在下面的代码 sn-p 中实现这个功能:
public class MonitoringInParallelExp {
public static void main(String[] args) throws InterruptedException {
MyClass1 myClass1 = new MyClass1();
ExecutorService service = Executors.newFixedThreadPool(1);
Future<String> future1 = service.submit(myClass1);
Thread.sleep(2000);
System.out.println("calling cancel in Main");
future1.cancel(true);
System.out.println("finally called cancel in Main");
service.shutdown();
}
}
class MyClass1 implements Callable<String> {
@Override
public String call() throws Exception {
try{
MyClass2 myClass2 = new MyClass2();
myClass2.method2();
} catch (Exception e){
if(e instanceof InterruptedException) {
System.out.println("call:"+"e instanceof InterruptedException="+"true");
throw e;
}
System.out.println("Got exception in method1. " + e);
}
System.out.println("returning Myclass1.method1.exit");
return "Myclass1.method1.exit";
}
}
class MyClass2 {
public void method2() throws Exception{
try{
MyClass3 myClass3 = new MyClass3();
myClass3.method3();
} catch (Exception e){
if(e instanceof InterruptedException) {
System.out.println("method2:"+"e instanceof InterruptedException="+"true");
throw e;
}
System.out.println("Got exception in method2. " + e);
// in case the exception isn't InterruptedExceptionm, do some work here
}
}
}
class MyClass3 {
public void method3() throws Exception{
try{
Thread.sleep(10000);
} catch (Exception e){
if(e instanceof InterruptedException) {
System.out.println("method3:"+"e instanceof InterruptedException="+"true");
throw e;
}
System.out.println("Got exception in method3. " + e);
throw new MyException();
}
}
}
class MyException extends Exception {
}
【问题讨论】:
标签: java multithreading exception executorservice futuretask