我有一个程序,其中创建一个数组,将其克隆到所需数量的相同数组中,然后以不同的方式排序。
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 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 ); }
}
}
}