11 Ekim 2023 Çarşamba

Thread.ofVirtual metodu - Builder Yöntemi

Giriş
Thread için Builder yöntemini kullanabilmeyi sağlar. Eğer Builder ile uğraşmak istemiyorsak direkt
şöyle yaparız
Thread thread = Thread.startVirtualThread(() -> {
  // your code here
});
Örnek
Şöyle yaparız
Runnable fn = () -> {
  // your code here
};

Thread thread = Thread.ofVirtual(fn)
                      .start();
name metodu
Örnek
Şöyle yaparız
Thread newThread = Thread.ofVirtual()
 .name(jmThread.getThreadName())
 .unstarted(jmThread);
unstarted metodu
Örnek
Şöyle yaparız
public static void main(String[] args) throws Exception {
  var threads = IntStream.range(0, 5).mapToObj(index->Thread.ofVirtual().unstarted(() -> {
    ...
  })).toList();

  threads.forEach(Thread::start);
  for (Thread thread : threads) {
    thread.join();
  }
}
Çıktı şöyle
src [main] ~/jdk-19.jdk/Contents/Home/bin/java --enable-preview main
VirtualThread[#23]/runnable@ForkJoinPool-1-worker-3
VirtualThread[#22]/runnable@ForkJoinPool-1-worker-2
VirtualThread[#21]/runnable@ForkJoinPool-1-worker-1
VirtualThread[#25]/runnable@ForkJoinPool-1-worker-5
VirtualThread[#24]/runnable@ForkJoinPool-1-worker-4
VirtualThread[#25]/runnable@ForkJoinPool-1-worker-3
VirtualThread[#24]/runnable@ForkJoinPool-1-worker-2
VirtualThread[#21]/runnable@ForkJoinPool-1-worker-4
VirtualThread[#22]/runnable@ForkJoinPool-1-worker-2
VirtualThread[#23]/runnable@ForkJoinPool-1-worker-3

Hiç yorum yok:

Yorum Gönder