Java 中是否有任何来处理一些线程已经结束?
Future<String> test = workerPool.submit(new TestCalalble());
test.addActionListener(new ActionListener()
{
public void actionEnd(ActionEvent e)
{
txt1.setText("Button1 clicked");
}
});
我知道,这是不可能处理这样的,但我想通知时,一些线程结束。
通常我用这个 Timer 类来检查每个 Future 的状态。但这不是很好的方式。谢谢

您可以使用CompletionService。
CompletionService<Result> ecs
= new ExecutorCompletionService<Result>(e);
ecs.submit(new TestCallable());
if (ecs.take().get() != null) {
// on finish
}
另一种选择是使用来自 Guava 的ListenableFuture。
代码示例:
ListenableFuture future = Futures.makeListenable(test);
future.addListener(new Runnable() {
public void run() {
System.out.println("Operation Complete.");
try {
System.out.println("Result: " + future.get());
} catch (Exception e) {
System.out.println("Error: " + e.message());
}
}
}, exec);
就个人而言,我更喜欢番石榴解决方案。
这是一个geekish。使用起来非常不可见,但是有趣而聪明
Thread t = ...
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler(){
@Override
public void uncaughtException(Thread t, Throwable e) {
t.getThreadGroup().uncaughtException(t, e);//this is the default behaviour
}
protected void finalize() throws Throwable{
//cool, we go notified
//handle the notification, but be worried, it's the finalizer thread w/ max priority
}
});
通过 PhantomRefernce 可以更好地达到效果
希望你有一点微笑:)
旁注:您要问的是不是线程结束,而是任务完成事件,最好是覆盖decorateTask
或afterExecute
无需添加大量额外的代码,您可以自己制作一个快速线程,如下所示:
//worker thread for doings
Thread worker = new Thread(new Runnable(){
public void run(){/*work thread stuff here*/}
});
worker.start();
//observer thread for notifications
new Thread(new Runnable(){
public void run(){
try{worker.join();}
catch(Exception e){;}
finally{ /*worker is dead, do notifications.*/}
}).start();

您可以实现观察者模式来报告完成情况。
public intece IRunComplete {
public void reportCompletion(String message);
}
让 Thread 调用方实现此接口。
在 run () 方法中,你最后调用这个方法。所以现在你确切地知道这个线程什么时候结束。
试试看。我实际上正在使用这个,它工作正常。
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(1条)