Java 虚拟线程总结

Java 虚拟线程介绍

虚拟线程(Virtual Thread)是Java 19引入的一种轻量级线程,它在很多其他语言中被称为协程、纤程、绿色线程、用户态线程等。
线程的特点:

  • 线程是由操作系统创建并调度的资源;
  • 线程切换会耗费大量CPU时间;
  • 一个系统能同时调度的线程数量是有限的,通常在几百至几千级别。

虚拟线程的特点:

  • 虚拟线程是由 Java 运行时(JVM)而不是操作系统创建并调度的资源。
  • 虚拟线程的切换耗费的 CPU 时间远远小于传统操作系统线程。
  • 一个 Java 应用可以创建数量非常庞大的虚拟线程,远远超过传统操作系统线程的几百至几千级别。

Java 虚拟线程的创建

可以使用以下几种方式创建虚拟线程

通过 Thread.ofVirtual().start() 方法

// 传入Runnable实例并立刻运行:
Thread vt = Thread.ofVirtual().start(() -> {
	System.out.println("Start virtual thread:" + Thread.currentThread());
	try {
		Thread.sleep(10);
	} catch (InterruptedException e) {
		throw new RuntimeException(e);
	}
	System.out.println("End virtual thread:" + Thread.currentThread());
});

System.out.println("Main thread:" + Thread.currentThread());
try {
	vt.join();
} catch (InterruptedException e) {
	throw new RuntimeException(e);
}

通过 Thread.ofVirtual().unstarted() 方法

// 传入Runnable实例
Thread vt = Thread.ofVirtual().unstarted(() -> {
	System.out.println("Start virtual thread:" + Thread.currentThread());
	try {
		Thread.sleep(10);
	} catch (InterruptedException e) {
		throw new RuntimeException(e);
	}
	System.out.println("End virtual thread:" + Thread.currentThread());
});
// 运行虚拟线程
vt.start();
System.out.println("Main thread:" + Thread.currentThread());
try {
	vt.join();
} catch (InterruptedException e) {
	throw new RuntimeException(e);
}

虚拟线程的 ThreadFactory 创建虚拟线程

// 创建一个ThreadFactory用于创建虚拟线程
ThreadFactory virtualThreadFactory = Thread.ofVirtual().factory();

// 使用ThreadFactory创建一个线程,传入 Runnable对象
Thread vt = virtualThreadFactory.newThread(() -> {
	System.out.println("Start virtual thread:" + Thread.currentThread());
	try {
		Thread.sleep(10);
	} catch (InterruptedException e) {
		throw new RuntimeException(e);
	}
	System.out.println("End virtual thread:" + Thread.currentThread());
});
// 运行虚拟线程
vt.start();
System.out.println("Main thread:" + Thread.currentThread());
try {
	vt.join();
} catch (InterruptedException e) {
	throw new RuntimeException(e);
}

使用 Executors.newVirtualThreadPerTaskExecutor() 创建虚拟线程执行器

// 创建虚拟线程调度器
ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();

// 向调度器提交 Runnable对象
executor.submit(() -> {
	System.out.println("Start virtual thread:" + Thread.currentThread());
	try {
		Thread.sleep(10);
	} catch (InterruptedException e) {
		throw new RuntimeException(e);
	}
	System.out.println("End virtual thread:" + Thread.currentThread());
});
System.out.println("Main thread:" + Thread.currentThread());

//关闭虚拟线程调度器
executor.shutdown();
// 等待调度器关闭完成
while (!executor.isTerminated()) {
	try {
		Thread.sleep(100);
	} catch (InterruptedException e) {
		throw new RuntimeException(e);
	}
}
posted @ 2024-11-01 00:53  Jacob-Chen  阅读(88)  评论(0)    收藏  举报