Why don't my 1_000_000 Virtual Threads print a 1_000_000 outcomes?

113 Views Asked by At

I was tinkering with Virtual Threads and made this bit of code:

        List<Thread> threads = new ArrayList<>();

        for(int i = 0; i < 1_000_000; i++){
            var thread = Thread.ofVirtual()
                    .unstarted(()->{
                            String n = Thread.currentThread().toString();
                        System.out.println(n);

                    });
            threads.add(thread);
        }
        for (var thread: threads){
            thread.start();
        }

I would expect this to print a million lines that look like VirtualThread[#31]/runnable@ForkJoinPool-1-worker-2 However, it prints an inconsistent amount of lines like that. Somewhere between 200 and 1000 lines, it varies for each run.

How come it doesn't print a million lines?

0

There are 0 best solutions below