-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVirtualThreadCallableDemo.java
More file actions
41 lines (37 loc) · 1.53 KB
/
Copy pathVirtualThreadCallableDemo.java
File metadata and controls
41 lines (37 loc) · 1.53 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
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class VirtualThreadCallableDemo {
public static void main(String[] args) {
// Use a virtual thread executor (Java 21+)
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
List<Callable<String>> tasks = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
int taskId = i;
tasks.add(() -> {
String threadName = Thread.currentThread().threadName();
// Simulate work that can be done concurrently
Thread.sleep(500L * taskId);
return "Task " + taskId + " completed on " + threadName;
});
}
try {
List<Future<String>> futures = executor.invokeAll(tasks);
for (Future<String> future : futures) {
try {
System.out.println(future.get());
} catch (ExecutionException e) {
System.err.println("Task execution failed: " + e.getCause());
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("Execution interrupted");
}
}
}
}