前言
一直以来,Java的线程一直被诟病,因为Java创建一个线程需要耗费的资源比较多,在同等资源下,go的协程比Java的线程性能好很多,而且耗的资源少,但是在jdk21中,Java推出了虚拟线程新属性,虚拟线程是轻量级线程,极大地减少了编写、维护和观察高吞吐量并发应用的工作量,虚拟线程是由JEP 425提出的预览功能,并在JDK19中发布,JDK 21中最终确定虚拟线程,JDK19要使用虚拟线程,需要开启预览模式,即--enable-preview
jdk21虚拟线程使用
单个虚拟线程创建
JDK21可以使用Thread创建单个虚拟线程,如
public class VirThreadDemo {
public static void main(String[] args) {
Thread.ofVirtual().start(() -> {
System.out.println(12);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("=========执行结束");
});
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("main方法执行结束");
}
}
虚拟线程是个守护进进程,main方法执行结束,虚拟线程也就结束了,可以使用CountDownLatch保证虚拟线程执行完
*/
public class ThreadVirDemo {
static CountDownLatch countDownLatch = new CountDownLatch(2);
public static void main(String[] args) {
Thread.ofVirtual().start(() -> {
System.out.println(12);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
countDownLatch.countDown();
});
// 也可以指定虚拟线程的名字
Thread.ofVirtual().name("test vir").start(() -> {
System.out.println(13);
System.out.println(Thread.currentThread().getName());
countDownLatch.countDown();
});
try {
countDownLatch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
ThreadFactory创建
public class ThreadPoolExecutorDemo {
public static void main(String[] args) {
ThreadFactory factory = Thread.ofVirtual().factory();
ExecutorService pools = new ThreadPoolExecutor(3,
5,
8,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(6),
factory,
new ThreadPoolExecutor.AbortPolicy());
try (pools) {
pools.submit(() -> {
System.out.println(12);
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
创建虚拟线程线程池
使用Executors创建虚拟线程线程池
public class VirtualThreadsExample {
public static void main(String[] args) {
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 10_000).forEach(i -> {
executor.submit(() -> {
System.out.println("==========================");
return i;
});
});
}
}
}
使用虚拟线程比较轻量级,相对线程来讲,在同等资源下,虚拟线程显得更加有优势
总结
jdk21使用虚拟线程开发,可以更好的提高系统的性能,极大提高我们的开发效率,但是在开发中,jdk版本的使用以及技术的选型,还是适合自己就好