39

我的代码片段:

ExecutorService executor = Executors.newSingleThreadExecutor();
try {
    Task t = new Task(response,inputToPass,pTypes,unit.getInstance(),methodName,unit.getUnitKey());
    Future<SCCallOutResponse> fut = executor.submit(t);
    response = fut.get(unit.getTimeOut(),TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
    // if the task is still running, a TimeOutException will occur while fut.get()
    cat.error("Unit " + unit.getUnitKey() + " Timed Out");
    response.setVote(SCCallOutConsts.TIMEOUT);
} catch (InterruptedException e) {
    cat.error(e);
} catch (ExecutionException e) {
    cat.error(e);
} finally {
    executor.shutdown();
}

我应该如何处理代码中的InterruptedExceptionand ExecutionException

在什么情况下会抛出这些异常?

4

3 回答 3

59

ExecutionException并且InterruptedException是两个非常不同的东西。

ExecutionException包装正在执行的线程抛出的任何异常,因此,例如,如果您的线程正在执行某种导致IOException抛出 an 的 IO,那么它将被包装在 an 中ExecutionException并重新抛出。

AnInterruptedException并不表示出现任何问题。它可以为您提供一种方法,让您的线程知道何时该停止,以便它们可以完成当前工作并优雅地退出。假设我希望我的应用程序停止运行,但我不希望我的线程在某些事情中间放弃他们正在做的事情(如果我让它们成为守护线程会发生这种情况)。所以当应用程序关闭时,我的代码在这些线程上调用中断方法,在它们上设置中断标志,下次这些线程等待或休眠时,它们会检查中断标志并抛出一个InterruptedException,我可以用它来摆脱线程所从事的任何无限循环处理/睡眠逻辑。(如果线程不等待或睡眠,它可以定期检查中断标志。)所以它是一个实例用于更改逻辑流的异常。您完全记录它的唯一原因是在示例程序中向您展示正在发生的事情,或者如果您正在调试中断逻辑无法正常工作的问题。

于 2010-04-21T21:15:35.430 回答
8

InterruptedExceptioninterrupt如果在计算完成之前在等待线程上调用,将被抛出。

ExecutionException如果所涉及的计算(Task在这种情况下)本身抛出异常,则将被抛出。

您要如何处理这将完全取决于您的应用程序。

编辑:这是被打断的演示:

import java.util.concurrent.*;

public class Test
{
    public static void main(String[] args) throws Exception
    {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        Future<String> future = executor.submit(new SlowCallable());
        executor.submit(new Interruptor(Thread.currentThread()));
        try
        {
            System.out.println(future.get());
        }
        catch (InterruptedException e)
        {
            System.out.println("I was interrupted");
        }
    }

    private static class Interruptor implements Callable<String>
    {
        private final Thread threadToInterrupt;

        Interruptor(Thread threadToInterrupt)
        {
            this.threadToInterrupt = threadToInterrupt;
        }

        public String call() throws Exception
        {
            Thread.sleep(2000);
            threadToInterrupt.interrupt();
            return "interrupted other thread";
        }
    }

    private static class SlowCallable implements Callable<String>
    {
        public String call() throws Exception
        {
            Thread.sleep(5000);
            return "finished";
        }
    }
}
于 2010-04-19T06:41:42.693 回答
2

返回三种异常的示例代码。

import java.util.concurrent.*;
import java.util.*;

public class ExceptionDemo{
    public static void main(String args[]){
        int poolSize=1;
        int maxPoolSize=1;
        int queueSize=30;
        long aliveTive=60;
        ArrayBlockingQueue<Runnable> queue= new ArrayBlockingQueue<Runnable>(queueSize);
        ThreadPoolExecutor executor= new ThreadPoolExecutor(poolSize,maxPoolSize,aliveTive,
                        TimeUnit.MILLISECONDS,queue);
        List<Future> futures = new ArrayList<Future>();
        for ( int i=0; i < 5; i++){
            futures.add(executor.submit(new RunnableEx()));
        }
        for ( Iterator it = futures.iterator(); it.hasNext();){
            try {
                Future f = (Future)it.next();
                f.get(4000,TimeUnit.MILLISECONDS);
            }catch(TimeoutException terr){
                System.out.println("Timeout exception");
                terr.printStackTrace();
            }
            catch(InterruptedException ierr){
                System.out.println("Interrupted exception:");
                ierr.printStackTrace();
            }catch(ExecutionException err){
                System.out.println("Exeuction exception:");
                err.printStackTrace();
                Thread.currentThread().interrupt();
            }
        }
        executor.shutdown();
    }
}

class RunnableEx implements Runnable{
    public void run() {
        // code in here
        System.out.println("Thread name:"+Thread.currentThread().getName());
        try{
            Random r = new Random();
            if (r.nextInt(2) == 1){
                Thread.sleep(2000);
            }else{
                Thread.sleep(4000);
            }
            System.out.println("eee:"+1/0);
        }catch(InterruptedException irr){
            irr.printStackTrace();
        }
    }
}

输出:

Thread name:pool-1-thread-1
Timeout exception
Thread name:pool-1-thread-1
java.util.concurrent.TimeoutException
        at java.util.concurrent.FutureTask.get(FutureTask.java:201)
        at ExceptionDemo.main(ExceptionDemo.java:20)
Thread name:pool-1-thread-1
Exeuction exception:
java.util.concurrent.ExecutionException: java.lang.ArithmeticException: / by zero
        at java.util.concurrent.FutureTask.report(FutureTask.java:122)
        at java.util.concurrent.FutureTask.get(FutureTask.java:202)
        at ExceptionDemo.main(ExceptionDemo.java:20)
Caused by: java.lang.ArithmeticException: / by zero
        at RunnableEx.run(ExceptionDemo.java:49)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
        at java.util.concurrent.FutureTask.run(FutureTask.java:262)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:744)
Interrupted exception:
java.lang.InterruptedException
        at java.util.concurrent.FutureTask.awaitDone(FutureTask.java:400)
        at java.util.concurrent.FutureTask.get(FutureTask.java:199)
        at ExceptionDemo.main(ExceptionDemo.java:20)
Timeout exception
java.util.concurrent.TimeoutException
        at java.util.concurrent.FutureTask.get(FutureTask.java:201)
Thread name:pool-1-thread-1
        at ExceptionDemo.main(ExceptionDemo.java:20)
Thread name:pool-1-thread-1
Timeout exception
java.util.concurrent.TimeoutException
        at java.util.concurrent.FutureTask.get(FutureTask.java:201)
        at ExceptionDemo.main(ExceptionDemo.java:20)

TimeoutException:阻塞操作超时时抛出的异常。

在上面的例子中,一些任务花费了更多的时间(由于 4 秒的睡眠)并且阻塞了get()on的操作Future

要么增加超时,要么优化 Runnable 任务。

ExecutionException:尝试检索因抛出异常而中止的任务的结果时抛出的异常 => 计算抛出异常

在上面的例子中,这Exception是通过模拟的ArithmeticException: / by zero

一般来说,如果它像示例中引用的那样微不足道,您应该抓住它来解决根本原因。

InterruptedException:当线程正在等待、睡眠或以其他方式被占用,并且线程在活动之前或期间被中断时抛出。

在上面的例子中,这Exception是通过在ExecutionException.

一般来说,你应该抓住它不要对它采取行动。

于 2016-07-01T13:57:11.733 回答