目前,我有一个代码如下:

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();
}

我已经阅读了有关可运行对象的信息,该对象可用于将进程拆分为多个线程,这会将我的代码更改为如下所示:
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());
}

10-06 04:59
查看更多