gpt4 book ai didi

java - 几个Runnable完成后的返回值

转载 作者:行者123 更新时间:2023-11-29 10:09:32 25 4
gpt4 key购买 nike

目前我有如下代码:

public String getValue()
{
StringBuilder builder = new StringBuilder();
// 1st step
//some logic to retreive code from database returning value
//doing something with the returned value add it to collection
builder.append(someString1);
// 2nd step
//some logic to retreive code from database returning value
//doing something with the returned value add it to collection
builder.append(someString2);
// 3rd step
//some logic to retreive code from database returning value
//doing something with the returned value add it to collection
builder.append(someString3);

return builder.toString();
}

我读过有关可用于将进程拆分为多个线程的 Runnable 对象,这会将我的代码更改为如下内容:

public String getValue()
{
Thread firstTread = new Thread(new Process1());
firstTread.start();
Thread secondTread = new Thread(new Process1());
secondTread.start();
Thread thirdTread = new Thread(new Process1());
thirdTread.start();

// here i got confuse how to determine whether all thread allready finished
// before returning builder.toString();
}
//this is internal class
class Process1 implements Runnable
{
public void run()
{
//do something and add to StringBuilder
}
}

class Process2 implements Runnable
{
public void run()
{
//do something and add to StringBuilder
}
}

class Process3 implements Runnable
{
public void run()
{
//do something and add to StringBuilder
}
}

如何实现将进程拆分为多个线程的目标?

最佳答案

你要找的不是Runnable,而是一个Callable .与 Runnable 不同,Callable 返回一个值。这通常与 ExecutorService 一起使用(一个线程池)。

在线程池中维护您的线程总是好的,而不是像那样手动生成它们。这可以防止创建不必要且昂贵的线程。这个想法是,不是调用 Thread.start(),而是将 Callable 的实例提交给具有预定义线程数的 ExecutorService 实例。每次提交都会返回一个 Future目的。 Future 对象允许您等待已提交给 ExecutorService 的 Callable 实例的返回值。

这是您原始代码的修订版:

class Process1 implements Callable<String> {
@Override
public String call() throws Exception {
return "Some string from this callable";
}
}
// Insert implementation for Process2 and Process2 Callables
...

public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(3);

Future<String> process1Future = executor.submit(new Process1());
Future<String> process2Future = executor.submit(new Process2());
Future<String> process3Future = executor.submit(new Process3());

// It will wait here
String processedStringByProcess1 = process1Future.get();
String processedStringByProcess2 = process2Future.get();
String processedStringByProcess3 = process3Future.get();

StringBuilder builder = new StringBuilder();
builder.append(processedStringByProcess1);
builder.append(processedStringByProcess2);
builder.append(processedStringByProcess3);

System.out.println(builder.toString());
}

关于java - 几个Runnable完成后的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47259533/

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