Giriş
Virtual Threads aslında ForkJoinPool üzerinde çalışır. Project Loom ile geliyor
Şöyle yaparız
private static void virtualThreadsDemo(int numberOfThreads) {try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {IntStream.range(0, numberOfThreads).forEach(i -> {executor.submit(() -> {Thread.sleep(Duration.ofMillis(1));return i;});});}}
Örnek
Şöyle yaparız
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { for (int i = 1; i <= 10; i++) { String taskName = "Task" + i; executor.execute(() -> someWork(taskName)); } }
Çıktı şöyle
VirtualThread[#25]/runnable@ForkJoinPool-1-worker-4 executing Task4VirtualThread[#26]/runnable@ForkJoinPool-1-worker-5 executing Task5VirtualThread[#28]/runnable@ForkJoinPool-1-worker-7 executing Task7VirtualThread[#23]/runnable@ForkJoinPool-1-worker-2 executing Task2VirtualThread[#21]/runnable@ForkJoinPool-1-worker-1 executing Task1VirtualThread[#24]/runnable@ForkJoinPool-1-worker-3 executing Task3VirtualThread[#27]/runnable@ForkJoinPool-1-worker-6 executing Task6VirtualThread[#29]/runnable@ForkJoinPool-1-worker-8 executing Task8VirtualThread[#32]/runnable@ForkJoinPool-1-worker-3 executing Task10VirtualThread[#31]/runnable@ForkJoinPool-1-worker-8 executing Task9VirtualThread[#26]/runnable@ForkJoinPool-1-worker-1 completed Task5VirtualThread[#21]/runnable@ForkJoinPool-1-worker-1 completed Task1VirtualThread[#25]/runnable@ForkJoinPool-1-worker-9 completed Task4VirtualThread[#24]/runnable@ForkJoinPool-1-worker-2 completed Task3VirtualThread[#27]/runnable@ForkJoinPool-1-worker-2 completed Task6VirtualThread[#32]/runnable@ForkJoinPool-1-worker-9 completed Task10VirtualThread[#28]/runnable@ForkJoinPool-1-worker-1 completed Task7VirtualThread[#23]/runnable@ForkJoinPool-1-worker-7 completed Task2VirtualThread[#31]/runnable@ForkJoinPool-1-worker-6 completed Task9VirtualThread[#29]/runnable@ForkJoinPool-1-worker-1 completed Task8
Hiç yorum yok:
Yorum Gönder