Skip to content

Instantly share code, notes, and snippets.

@alphaqiu
Created December 9, 2023 10:38
Show Gist options
  • Save alphaqiu/cfd1648eaf850c195fabca9ef557fcf9 to your computer and use it in GitHub Desktop.
Save alphaqiu/cfd1648eaf850c195fabca9ef557fcf9 to your computer and use it in GitHub Desktop.
虚拟线程是Java17+开始的新功能,虚拟线程由JVM负责管理和维护,在用户层非系统层创建。非常轻量,用完即扔。
package com.example.terminal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/**
*
*/
public class Main {
public static void main(String[] args) {
virtualThread1();
virtualThreadFactory();
}
public static void virtualThread1() {
System.out.println("----测试虚拟线程第一种方式----");
try(var exe = Executors.newVirtualThreadPerTaskExecutor()){
for (int i = 0; i < 100; i++) {
int value = i;
exe.submit(() -> {
System.out.println("我是编号" + value);
});
}
}
System.out.println("第一种虚拟线程测试完成!");
}
public static void virtualThreadFactory() {
System.out.println("我在执行ThreadFactory相关测试");
ThreadFactory factory = Thread.ofVirtual().name("demo", 1).factory();
List<Thread> threads = new ArrayList<>(10);
for (int i = 0; i < 10; i++) {
int value = i;
var thread = factory.newThread(() -> {
System.out.println("工厂方法-我执行了"+value);
});
threads.add(thread);
}
threads.forEach(Thread::start);
threads.forEach(thread -> {
try {
thread.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment