package dev.elaine.concurrency;

import java.time.Duration;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;

public final class VirtualThreadSample {
    private VirtualThreadSample() {
    }

    public static void main(String[] args) throws InterruptedException {
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            var tasks = java.util.stream.IntStream.range(0, 1_000)
                    .mapToObj(index -> (Callable<Integer>) () -> {
                        Thread.sleep(Duration.ofMillis(10));
                        return index;
                    })
                    .toList();
            long sum = executor.invokeAll(tasks).stream().mapToLong(future -> {
                try {
                    return future.get();
                } catch (Exception exception) {
                    throw new IllegalStateException(exception);
                }
            }).sum();
            System.out.println("任务数=" + tasks.size() + "，校验和=" + sum);
        }
    }
}
