首页  

java 虚拟线程使用     所属分类 java 浏览量 657
https://www.davidvlijmincx.com/posts/create_virtual_threads_with_project_loom/


A thread in Java is just a small wrapper around a thread that is managed and scheduled by the OS. 
Project Loom adds a new type of thread to Java called a virtual thread, and these are managed and scheduled by the JVM.

To create a platform thread (a thread managed by the OS), 
you need to make a system call, and these are expensive. 
To create a virtual thread, you don't have to make any system call, 
making these threads cheap to make when you need them. 
These virtual threads run on a carrier thread. 
Behind the scenes, the JVM created a few platform threads for the virtual threads to run on. 
Since we are free of system calls and context switches, 
we can run thousands of virtual threads on just a few platform threads.

Runnable task = () -> System.out.println("Hello, world");

// Platform thread
(new Thread(task)).start();
Thread platformThread = new Thread(task);
platformThread.start();

// Virtual thread
Thread virtualThread = Thread.startVirtualThread(task);
Thread ofVirtualThread = Thread.ofVirtual().start(task);

// Virtual thread created with a factory
ThreadFactory factory = Thread.ofVirtual().factory();
Thread virtualThreadFromAFactory = factory.newThread(task);
virtualThreadFromAFactory.start();

Runnable task = () -> System.out.println("Hello, world");
ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor();
executorService.execute(task);


ThreadFactory factory = Thread.ofVirtual().factory();
Executors.newVirtualThreadPerTaskExecutor();
Executors.newThreadPerTaskExecutor(factory); // Same as newVirtualThreadPerTaskExecutor
Executors.newSingleThreadExecutor(factory);
Executors.newCachedThreadPool(factory);
Executors.newFixedThreadPool(1, factory);
Executors.newScheduledThreadPool(1, factory);
Executors.newSingleThreadScheduledExecutor(factory);


Structured Concurrency


With Threads being cheap to create, project Loom also brings structured concurrency to Java. 
With structured concurrency, you bind the lifetime of a thread to a code block. 
Inside your code block, you create the threads you need and leave the block when all the threads are finished or stopped.

上一篇     下一篇
git的几个实用命令

networking io with virtual threads

guice例子

project loom 那些事

JDK18 特性

scala map 操作