Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

10.12. Java 协程

		
package cn.netkiller.thread;

import static java.lang.Thread.*;

public class VirtualThreadsTest {
    public static void main(String[] args) throws InterruptedException {
        var virtualThread = startVirtualThread(() -> System.out.println("Hello from the virtual thread"));
        virtualThread.join();
    }
}		
		
		

运行演示

		
neo@MacBook-Pro-M2 thread % java --source 20 --enable-preview VirtualThreadsTest.java
注: VirtualThreadsTest.java 使用 Java SE 20 的预览功能。
注: 有关详细信息,请使用 -Xlint:preview 重新编译。
Hello from the virtual thread
		
		
		
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {

        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            IntStream.range(0, 10000).forEach(i -> {
                executor.submit(() -> {
                    Thread.sleep(Duration.ofSeconds(1));
                    return i;
                });
            });
        }
    }
}
		
		
		
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class VirtualThreadExample {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();

        executor.submit(() -> {
            System.out.println(Thread.currentThread().getName())
        });

        executor.shutdown();
    }
}		
		
		
		
Thread.ofVirtual().start(Runnable);
Thread.ofVirtual().unstarted(Runnable);		
		
		
		
Thread.ofVirtual().start(Runnable);
Thread.ofVirtual().unstarted(Runnable);