java 线程结束侦听器。爪哇
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5169359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Thread end listener. Java
提问by Denis
Are there any Listeners in Java to handle that some thread have been ended? Something like this:
Java 中是否有任何侦听器来处理某个线程已结束?像这样的东西:
Future<String> test = workerPool.submit(new TestCalalble());
test.addActionListener(new ActionListener()
{
public void actionEnd(ActionEvent e)
{
txt1.setText("Button1 clicked");
}
});
I know, that it is impossible to deal like this, but I want to be notified when some thread ended.
我知道,这样处理是不可能的,但我想在某个线程结束时收到通知。
Usually I used for this Timer class with checking state of each Future. but it is not pretty way. Thanks
通常我用这个 Timer 类来检查每个 Future 的状态。但这不是很好的方式。谢谢
回答by nanda
There is CompletionServiceyou can use.
有CompletionService您可以使用。
CompletionService<Result> ecs
= new ExecutorCompletionService<Result>(e);
ecs.submit(new TestCallable());
if (ecs.take().get() != null) {
// on finish
}
Another alternative is to use ListenableFuturefrom Guava.
另一种选择是使用Guava 的ListenableFuture。
Code example:
代码示例:
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);
Personally, I like Guava solution better.
就个人而言,我更喜欢 Guava 解决方案。
回答by Andrew
Without adding a lot of extra code you can make a quick listener thread yourself as follows:
无需添加大量额外代码,您可以自己创建一个快速侦听器线程,如下所示:
//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();
回答by Ambarish Deshpande
You can implement Observer Pattern to report completion.
您可以实施观察者模式来报告完成情况。
public interface IRunComplete {
public void reportCompletion(String message);
}
Let the Thread caller implement this interface.
让线程调用者实现这个接口。
and in run() method you call this method at the end. So now you exactly knows when this thread gonna end.
在 run() 方法中,您最后调用此方法。所以现在你确切地知道这个线程什么时候结束。
Try it. I am actually using this and it's working fine.
试试看。我实际上正在使用它并且它工作正常。
回答by bestsss
Here is a geekishlistener. Highly unadvisible to use but, funny and clever
这是一个极客的听众。非常不建议使用但是,有趣而聪明
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
}
});
The effect can be achived via PhantomRefernce better
效果可以通过PhantomRefernce更好的实现
hope you have a little smile :)
希望你有一点微笑:)
Side note: what you ask is NOT thread end, but task completion event and the best is overriding either decorateTask
or afterExecute
旁注:您要问的不是线程结束,而是任务完成事件,最好是覆盖decorateTask
或afterExecute
回答by Abhishek Sengupta
Use this Example:
使用这个例子:
public class Main {
public static void main(String[] args) {
CompletionListener completedListener = count -> System.out.println("Final Count Value: " + count);
HeavyWorkRunnable job = new HeavyWorkRunnable(completedListener);
Thread otherThread = new Thread(job);
otherThread.start();
}
static class HeavyWorkRunnable implements Runnable {
CompletionListener completionListener;
public HeavyWorkRunnable(CompletionListener completionListener) {
this.completionListener = completionListener;
}
@Override
public void run() {
int count = 0;
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Clock Tick #"+i);
count += 1;
}
if (completionListener != null) {
completionListener.onCompleted(count);
}
}
}
@FunctionalInterface
interface CompletionListener {
void onCompleted(int count);
}
}
回答by AlexR
No. Such listener does not exist. But you have 2 solutions.
不。这样的监听器不存在。但是您有 2 个解决方案。
- Add code that notifies you that thread is done in the end of
run()
method - Use
Callable
interface that returns result of typeFuture
. You can ask Future what the status is and use blocked methodget()
to retrieve result
- 添加通知您线程在
run()
方法结束时完成的代码 - 使用
Callable
返回类型结果的接口Future
。您可以询问 Future 的状态是什么,并使用阻止的方法get()
来检索结果
回答by mazaneicha
You have a join() method defined by Thread class for that. However, you don't have direct visibility to a thread executing your Callable in concurrency API case..
您有一个由 Thread 类定义的 join() 方法。但是,您无法直接看到在并发 API 情况下执行 Callable 的线程。