gpt4 book ai didi

java - 我怎么知道线程作业已经完成?

转载 作者:搜寻专家 更新时间:2023-10-31 19:32:37 25 4
gpt4 key购买 nike

在 B 类中,我如何知道线程的作业已完成?在属性之后,一些 worker 正在运行。在 B 类中,我需要知道 worker 是否完成?

public class A implements InitializingBean{
public void method1(){
...
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.print("test after properties set");
// send threads to executorService
ExecutorService executorService = Executors
.newFixedThreadPool(4);
for (int i = 0; i < 4; i++) {
Worker worker = new Worker();
executorService.submit(worker);
}
}
}
public class Worker implements Callable<Void>{
@Override
public void call(){
...
}
}
public class B{
public void methodB(){
A a = new A();
a.method1();
///Here How can i know the job of the workers are finished?
}
}

最佳答案

使用监听器/回调模式让线程向监听器报告完成。这个简单的例子应该显示过程:

public interface ThreadCompleteListener {
void workComplete();
}

public class NotifyingThread extends Thread {
private Set<ThreadCompleteListener> listeners;
// setter method(s) for adding/removing listeners to go here

@Override
public void run() {
// do stuff
notifyListeners();
}

private void notifyListeners() {
for (ThreadCompleteListener listener : listeners) {
listener.workComplete(); // notify the listening class
}
}
}

在你的听力课上:

NotifyingThread t = new NotifyingThread();
t.addListener(new ThreadCompleteListener() {
void workComplete() {
// do something
}
});

t.start();

关于java - 我怎么知道线程作业已经完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31754102/

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