首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >线程池-异步任务(I)

线程池-异步任务(I)

原创
作者头像
顾老师的猫
修改2024-10-30 09:23:42
修改2024-10-30 09:23:42
2050
举报

先从线程池开始聊起

声明一个线程池,这个没问题,前面说过,用static也行,用spring来托管也可以

提交任务

2个方法:execute和submit

任务

参数

异常

返回值

execute

提交不需要返回结果的任务

实现Runnable接口

RuntimeException或Error都传给调用者

无返回值

submit

提交需要返回值或处理异常的任务

无需返回值用Runnable接口,需返回值用Callable接口

ExecutionException,用Future.get()获取

返回Future对象

来看代码实现吧

代码语言:java
复制
// Runnable 任务
executor.execute(() -> {  
    System.out.println("executed by " + Thread.currentThread().getName());  
 }); 

// Callable 任务
Future<String> future = executor.submit(() -> {  
    TimeUnit.SECONDS.sleep(1); 
    return "Callable task result";  
});
try {  
    String result = future.get();
} catch (InterruptedException | ExecutionException e) {  
    e.printStackTrace();  
}  

Lambda匿名类

上面的是Java8的Lambda表达式-匿名类,() -> { ... }

  • () 表示call()方法没有参数;
  • { ... } 是Lambda体,包含call()方法的实现; Java编译器会自动地将它转换为一个实现了Callable<String>接口匿名类的实例。

业务上会用函数,直接写到submit里面去。

Future

设置超时时间

代码语言:java
复制
try {  
    // 尝试在2秒内获取任务结果  
    String result = future.get(2, TimeUnit.SECONDS);  
    System.out.println("Task completed with result: " + result);  
} catch (TimeoutException e) {  
    // 任务在超时时间内没有完成  
    System.err.println("Task timed out!");  
    future.cancel(true); // true表示如果任务正在运行则中断它  
} catch (InterruptedException | ExecutionException e) {  
    e.printStackTrace();  
} finally {  
    executorService.shutdown();  
}  

CompletableFuture

代码语言:java
复制
CompletableFuture<String> future = CompletableFuture.supplyAsync(  
    () -> {  
        TimeUnit.SECONDS.sleep(1); 
        return "CompletableFuture task";  
    },  
    executor // 指定使用自定义的 ThreadPoolExecutor  
); 
// 处理异步任务的结果  
future.thenAccept(result -> {  
    System.out.println(" result: " + result);  
}).exceptionally(ex -> {  
    System.err.println(" failed: " + ex.getMessage());  
    return null; // 异常处理
});  

设置超时时间

代码语言:java
复制
public void process() {
    Future<String> future = executor.submit(() -> {
        return "submit ok";
    });
    try {
        future.get(1, TimeUnit.SECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        throw new RuntimeException(e);
    }
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 提交任务
  • Future
  • CompletableFuture
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档