专注于分布式,性能优化,代码之美

线程池submit()使用案例

submit()使用案例
public class Test {
private static final String SUCCESS = "success";

public static void main(String[] args) {

ExecutorService executorService = Executors.newFixedThreadPool(3);

System.out.println("------------------任务开始执行---------------------");

Future<String> future = executorService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(5000);
System.out.println("submit方法执行任务完成" + " thread name: " + Thread.currentThread().getName());
return SUCCESS;
}
});

try {
String s = future.get();
if (SUCCESS.equals(s)) {
String name = Thread.currentThread().getName();
System.out.println("经过返回值比较,submit方法执行任务成功 thread name: " + name);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}

System.out.println("-------------------main thread end---------------------");
}
}

打印结果:

------------------任务开始执行---------------------
call()调用开始: 1496899867882
submit方法执行任务完成: 1496899872897 thread name: pool-1-thread-1
经过返回值比较,submit方法执行任务成功 thread name: main
-------------------main thread end---------------------
1
2
3
4
5
6
主线程会一直阻塞,等待线程池中的任务执行完后,在执行后面的语句。
 

posted on 2021-04-12 14:32  xiaohouye  阅读(1138)  评论(0编辑  收藏  举报

导航

今日之劳累是为了铸造明日之辉煌,不管年龄多少,都无法阻挡我对软件艺术的追求!