0

我对我的代码有疑问。

我有两个从 main 方法运行的线程,我想捕获 main 方法的两个线程中的任何一个线程中可能发生的异常。

Future<Object> incoming=Executors.newSingleThreadExecutor().submit(new Task1(param1));
Future<Object> outgoing=Executors.newSingleThreadExecutor().submit(new Task2(param2));

问题是,如果我对异常使用 Future Object 并调用 get() 方法,它将阻塞我的代码,并且我不知道线程 2 是否在线程 1 之前完成/抛出异常。

我怎样才能优雅地处理这个而不是这个?

while(!(incoming.isDone() || outgoing.isDone())){}
4

2 回答 2

2

如果您想在异常发生时立即处理而不是等待任何其他任务完成,我会异步处理异常。

 ExecutorService oneService = ...

 oneService.submit(new Runnable() {
    public void run() {
        try {
            new Task(param1).run();
        } catch(Exception e) {
            // handle exception asynchronously
        }
    }        
 });
于 2012-07-25T13:35:13.197 回答
0

这个怎么样:

所有线程之间共享的队列(确保线程安全!),

Queue<Throwable> exceptionsToProcess;

然后,用 while 循环锁定你的 main 方法:

//start threads, pass them the queue


while(true)
{
    Throwable t;
    while((t = exceptionsToProcess.poll()) == null);
    //process t
}

异常将按正确的顺序处理,但如果您不注意线程安全,您将面临 ConcurrentModificationException 的风险。

编辑:这可能是一个有用的队列类:http ://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/LinkedBlockingQueue.html

于 2012-07-25T13:38:59.530 回答