gpt4 book ai didi

java - 线程中的异常处理

转载 作者:行者123 更新时间:2023-11-29 06:04:03 25 4
gpt4 key购买 nike

我们正在开展一个项目,从 Java 应用程序处理虚拟机管理器。

目前,我们遇到了一些指令必须被视为任务的问题,因为它们需要更多时间。这些任务也可能以错误结束或成功,除非我们向 VM 管理程序请求任务状态,否则我们无法知道应用程序的结果。

为了拥有一个流畅的应用程序,我们希望有一个 CommandManager 来处理在单独线程中对这些管理程序的不同请求。问题在于这些 Command 可能会返回特定的错误,例如我们过去常常在 View 中捕获以向用户显示相关信息,但是当我们在 Commands 界面上实现 Runnable 时,我们不能抛出任何错误该线程的异常返回以到达 View 。

我可以做些什么来不断通知用户所发生的错误及其性质?

对不起我的英语!

让我们看下面的代码作为一个简短的例子:

首先是命令

class ChangeMemorySize extends Command {
private String name;
private int memorySizeMb;

public ChangeMemorySize(Hypervisor hypervisor, String server,
String name, int memory) {
super(hypervisor, server);
this.name = name;
this.memorySizeMb = memory;
}
protected void execute() throws ConnectionException,OperationException{

//Some code here

}
public void run() //CANT THROW ANYTHING HERE :throws VmConfigFault,
try{
execute();
}catch{Exception e){
// I have to catch it all here!
}

这不是真正的代码,这只是一个例子。该命令随后将传递给经理,经理将在另一个线程中运行它。但是我放弃了我用来通知用户那里真正发生的事情的所有具体异常!

最佳答案

使用 ExecutorService 并执行以下两项操作之一。

首先您可以将所有结果存储在 Future 中,当您想知道是否发生异常时只需调用 Future.get() 并处理任何异常。

其次您可以使用 ThreadFactory 创建 ExecutorService,您可以在其中将其设置为已知的 UncaughtExceptionHandler

       final UncaughtExceptionHandler handler = new UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
// notify error
}
});
Executor executor = Executors.newFixedThreadPool(1, new ThreadFactory() {
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setUncaughtExceptionHandler(handler);
return thread;
}
});

关于java - 线程中的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9134379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com