如何让main等待线程执行,但这些线程必须同时启动

问题描述 投票:0回答:1

我有一个程序,其中创建一个数组,将其克隆到所需数量的相同数组中,然后以不同的方式排序。

https://github.com/zotov88/algorithms

public class SortingRunner {

    final static int CAPACITY = 10_000;
    final static int FROM = -100;
    final static int TO = 100;
    final static int COUNT_ARRAYS = 4;

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

        int[][] arrays = Utils.generateTheSameRandomArrays(CAPACITY, FROM, TO, COUNT_ARRAYS);

         List<Sorting> sortingList = List.of(
                new BubbleSort(arrays[0]),
                new SelectionSort(arrays[1]),
                new MergeSort(arrays[2]),
                new QuickSort(arrays[3])
        );

        for (Sorting sorting : sortingList) {
            Thread t = new Thread(() -> Utils.speedTest(sorting));
            t.start();
            t.join();
        }

        Utils.printArrays(arrays);
    }
}

在这一段代码中,线程首先被逐个处理,然后在main中开始数组的打印。


        for (Sorting sorting : sortingList) {
            Thread t = new Thread(() -> Utils.speedTest(sorting));
            t.start();
            t.join();
        }

        Utils.printArrays(arrays);

我希望在每个线程中同时对数组进行排序,并且 main 等待它们完成然后打印。

java multithreading concurrency
1个回答
0
投票

Java 5 中添加了 Executors 框架来支持此类工作。

将您的任务定义为

Runnable
Callable
对象。将它们提交给具有您所需行为的执行器服务对象。

通常最好使用

Executors
实用程序类来实例化执行器服务。这里我们使用一个执行器服务,为每个任务创建一个新的虚拟线程

提交任务时,您会得到一个

Future
对象。使用该对象来检查任务的进度。对于
Callable
,请使用该
Future
对象来访问任务结果。

package work.basil.example.threading;

import java.time.Instant;
import java.util.List;
import java.util.concurrent.*;

public class BunchOfTasks
{
    public static void main ( String[] args )
    {
        List < Callable < Instant > > tasks =
                List.of (
                        ( ) -> {
                            System.out.println ( "x" );
                            return Instant.now ( );
                        } ,
                        ( ) -> {
                            System.out.println ( "y" );
                            return Instant.now ( );
                        } ,
                        ( ) -> {
                            System.out.println ( "z" );
                            return Instant.now ( );
                        }
                );

        List < Future < Instant > > futures = List.of ( );
        try (
                ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor ( ) ;
        )
        {
            futures = executorService.invokeAll ( tasks );
        } catch ( InterruptedException e )
        {
            throw new RuntimeException ( e );
        }

        // Report results.
        for ( Future < Instant > instantFuture : futures )
        {
            try { System.out.println ( instantFuture.get ( ).toString ( ) ); } catch ( InterruptedException | ExecutionException e ) { throw new RuntimeException ( e ); }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.