-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathJep425Demo.java
87 lines (69 loc) · 2.96 KB
/
Jep425Demo.java
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package com.di1shuai.java19.virthread;
import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.stream.IntStream;
public class Jep425Demo {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
firstVirtualThread();
System.out.printf("VirtualThread finished, time cost %d ms\n",
System.currentTimeMillis() - startTime);
firstThread();
System.out.printf("Thread finished, time cost %d ms\n",
System.currentTimeMillis() - startTime);
}
public static void firstVirtualThread() {
// 创建10000个虚拟线程
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 10_000).forEach(i -> {
executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return i;
});
});
} // try-with-resources,会隐式调用executor.close()
}
public static void firstThread() {
// 创建10000个线程
try (var executor = Executors.newFixedThreadPool(1000)) {
IntStream.range(0, 10_000).forEach(i -> {
executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return i;
});
});
} // try-with-resources,会隐式调用executor.close()
}
private static void infoCurrentThread() {
Thread thread = Thread.currentThread();
System.out.printf("线程名称: %s,是否虚拟线程: %s\n",
thread.getName(), thread.isVirtual());
}
private static void waysToCreateVirtualThread() {
// 方式一:直接启动,虚拟线程名称为""
Thread.startVirtualThread(() -> infoCurrentThread());
// 方式二:Builder模式构建
Thread vt = Thread.ofVirtual().allowSetThreadLocals(false)
.name("VirtualWorker-", 0)
.inheritInheritableThreadLocals(false)
.unstarted(() -> infoCurrentThread());
vt.start();
// 方式三:Factory模式构建
ThreadFactory factory = Thread.ofVirtual().allowSetThreadLocals(false)
.name("VirtualFactoryWorker-", 0)
.inheritInheritableThreadLocals(false)
.factory();
Thread virtualWorker = factory.newThread(() -> infoCurrentThread());
virtualWorker.start();
// 方式四:newVirtualThreadPerTaskExecutor
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
executor.submit(() -> infoCurrentThread());
}
// 方式五:构建"虚拟线程池"
ExecutorService executorService = Executors.newThreadPerTaskExecutor(factory);
executorService.submit(() -> infoCurrentThread());
infoCurrentThread();
}
}