-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVirtualThreadsDemo.java
More file actions
72 lines (63 loc) · 1.71 KB
/
Copy pathVirtualThreadsDemo.java
File metadata and controls
72 lines (63 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package java19.virtualthreads;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
/**
* Java 19 Virtual Threads (Preview) Demonstrates lightweight virtual threads
*/
public class VirtualThreadsDemo
{
public static void main(String[] args)
{
// 1. Create virtual thread directly
System.out.println("=== Virtual Thread Creation ===");
Thread virtualThread = Thread.ofVirtual()
.name("worker-", 0)
.start(() -> {
System.out.println("Running on virtual thread: " + Thread.currentThread().getName());
});
try
{
virtualThread.join();
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
// 2. Using virtual thread executor
System.out.println("\n=== Virtual Thread Executor ===");
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor())
{
for (int i = 0; i < 5; i++)
{
final int taskId = i;
executor.submit(() -> {
System.out.println("Task " + taskId + " on virtual thread: " +
Thread.currentThread().getName());
try
{
Thread.sleep(100); // Simulate I/O operation
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
});
}
}
// 3. Builder pattern
System.out.println("\n=== Builder Pattern ===");
Thread.Builder builder = Thread.ofVirtual().name("task-", 0);
Thread vt1 = builder.start(() -> System.out.println("Task 1"));
Thread vt2 = builder.start(() -> System.out.println("Task 2"));
try
{
vt1.join();
vt2.join();
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
System.out.println("\nVirtual threads are lightweight and perfect for I/O-bound operations!");
}
}