0

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?

Mark Rensen
  • 129
  • 1
  • 7
  • 5
    You should wait for each of those threads to finish. Currently, your application just exits, taking those still running threads with it. – Jorn Jun 08 '23 at 13:56
  • Thanks, for the quick response. That makes sense. I've used join() now and it works – Mark Rensen Jun 08 '23 at 14:25

0 Answers0