import java.time.Duration;
import java.time.Instant;
import java.util.Set;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.IntStream;

public class MaxThreads {

    // --enable-preview

    private static final void exitWithMessage() {
          System.out.println("Expected argument: virt or plat");
          System.exit(1);
    }
    public static void main(String[] args) throws InterruptedException {
        System.out.println(Arrays.toString(args));
        if (args.length != 2) {
          exitWithMessage();
        }

        var builder = switch(args[0]) {
          case "virt" -> Thread.ofVirtual();
          case "plat" -> Thread.ofPlatform();
          default -> null;
        };

        var count = Integer.parseInt(args[1]);
        
        if (builder == null) {
          exitWithMessage();
        }
        // virtual thread
        var threads =
              IntStream.range(0, count)
                    .mapToObj(index ->
                          builder
                                .name("platform-", index)
                                .unstarted(() -> {
                                    try {
                                        Thread.sleep(2_000);
                                    } catch (InterruptedException e) {
                                        throw new RuntimeException(e);
                                    }
                                }))
                    .toList();

        Instant begin = Instant.now();
        threads.forEach(Thread::start);
        for (Thread thread : threads) {
            thread.join();
        }
        Instant end = Instant.now();
        System.out.println("Duration = " + Duration.between(begin, end));
    }
}
