gpt4 book ai didi

java - 从子线程返回响应的设计模式

转载 作者:行者123 更新时间:2023-12-01 06:13:24 25 4
gpt4 key购买 nike

我正在寻找一种设计模式,其中父线程将生成多个子线程。每个子线程都会执行一些计算并返回适当的结果。

父线程将等待子线程完成。所有子线程完成后,将合并结果发送给父线程。

然后父线程将继续处理合并结果。

最佳答案

检查Thread类的join方法。这是一个工作示例:

import java.lang.*;

public class Threads {

public void callChildren() throws Exception {

Thread t = new Thread(new ChildThread());
t.start();
t.join();
System.out.print(t.getName());
System.out.println(", status = " + t.isAlive());
}

public static void main(String[] args) throws Exception{

for(int i = 0 ; i < 4; i ++) {
new Threads().callChildren();
}

System.out.println("Printing from Parent thread after all child thread are complete.");
}


private class ChildThread implements Runnable{

@Override
public void run() {
System.out.println("Thread started:::"+Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread ended:::"+Thread.currentThread().getName());
}
}

}

关于java - 从子线程返回响应的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30819769/

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