java 21 虚拟线程初体验

基本特性,前提知识

https://openjdk.org/jeps/444

https://www.cnblogs.com/didispace/p/17735173.html

不适应场景

java 21不适合 CPU 密集计算型任务,不过绝大多数的使用都不会是cpu密集计算场景🐶。

初体验

任务描述:

一共有三个任务,任务三的值需要任务一和任务二的结果,并且任务三有500ms的超时时间,一但超时直接返回。

代码实现:

import java.util.concurrent.*;
 
public class VirtualTest {
    public static void main(String[] args) throws Exception {
        final ExecutorService virtualExecutor = Executors.newVirtualThreadPerTaskExecutor();
        DataDto dataDto = new DataDto();
        // 任务一
        var futurePre = virtualExecutor.submit(()->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            dataDto.num1 = 10;
        });
        // 任务二
        var futureNext = virtualExecutor.submit(()->{
            try {
                futurePre.get();
                Thread.sleep(1000);
                dataDto.num2 = dataDto.num1+5;
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            }
        });
        // 任务三
        var futureEnd = virtualExecutor.submit(()->{
            try {
                futureNext.get();
                futurePre.get();
                dataDto.sum = dataDto.num1+ dataDto.num2;
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            }
        });
        try {
            // 设置超时时间
            futureEnd.get(500,TimeUnit.MILLISECONDS);
            System.out.println(dataDto.sum);
        }catch (Exception e){
            System.out.println("线程超时");
        }
    }
    // 数据暂存地址
    static class DataDto{
        public Integer num1;
        public Integer num2;
        public Integer sum;
    }
}
posted @ 2024-04-25 14:27  度一川  阅读(32)  评论(0)    收藏  举报