【JDK21】初体验

IDEA 2023.2.2已支持JDK21

Java 21发布,IntelliJ IDEA 2023.2.2已完美支持。
想要开发Java 21代码的开发者可以升级了!

Java新特性

Java 9 - 21:新特性解读

虚拟线程

虚拟线程创建

(1)使用静态构建器方法
(2)使用Thread.ofVirtual()
(3)使用虚拟线程工厂
(4)与ExecutorService结合使用

public static void main(String[] args) throws InterruptedException {
        Runnable runnable = () -> {
            System.out.println("Hello, jdk21");
        };
        // 使用静态构建器方法
        Thread.startVirtualThread(runnable);
        // 使用Thread.ofVirtual()
        Thread.ofVirtual().name("jdk21-virtual-thread").start(runnable);
        // 使用虚拟线程工厂
        ThreadFactory virtualThreadFactory = Thread.ofVirtual().name("jdk21", 0).factory();
        Thread factoryThread = virtualThreadFactory.newThread(runnable);
        factoryThread.start();
        // 与ExecutorService结合使用
        try (ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < 100; i++) {
                executorService.submit(runnable);
            }
        }
        ExecutorService executorService = Executors.newThreadPerTaskExecutor(virtualThreadFactory);
        for (int i = 0; i < 10; i++) {
            executorService.submit(() -> {
                System.out.println(Thread.currentThread().getName() + " is running...");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " is done.");
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.MINUTES);
    }

虚拟线程测试

public static void main(String[] args) {
        int timesCount = 1000;
        long l1 = System.currentTimeMillis();
        for (int i = 0; i < timesCount; i++) {
            int finalI = i;
            Thread.ofPlatform().name("平台线程").start(() -> {
                System.out.println("线程名称:" + Thread.currentThread().getName() + "线程ID" + Thread.currentThread().threadId() + "执行第" + finalI + "个平台线程");
            });
        }
        long l2 = System.currentTimeMillis();
        for (int i = 0; i < timesCount; i++) {
            int finalI = i;
            Thread.ofVirtual().name("虚拟线程").start(() -> {
                System.out.println("线程名称:" + Thread.currentThread().getName() + "线程ID" + Thread.currentThread().threadId() + "执行第" + finalI + "个平台线程");
            });
        }
        System.out.println("线程分别执行 " + timesCount + " 次压测...");
        System.out.println("平台线程执行耗时:" + (System.currentTimeMillis() - l1) + "毫秒");
        System.out.println("虚拟线程执行耗时:" + (System.currentTimeMillis() - l2) + "毫秒");
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

你可能感兴趣的:(java)