package concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestThreadPoolWithRunable {
public static void main(String[] args) {
ExecutorService pool = Executors.newCachedThreadPool();
for (int i = 1; i <= 3; i++) {
// 向线程池中提交3个任务(任务:打印自己的线程名)
pool.execute(new Runnable() {
@Override
public void run() {
System.out.println("线程名: " + Thread.currentThread().getName());
}
});
}
pool.shutdown();
}
}
线程名: pool-1-thread-2
线程名: pool-1-thread-3
线程名: pool-1-thread-1
创建一个线程池,线程池中的线程数量固定为6,向线程池中提交6个任务,每个任务都是计算1~10,最后将这6个任务的计算结果分别打印出来。
package concurrent;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TestThreadPoolWithCallable {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService pool = Executors.newFixedThreadPool(6);
ArrayList<Future<Integer>> futureList = new ArrayList<Future<Integer>>();
for (int i = 0; i < 6; i++) {
Future<Integer> result = pool.submit(() -> {
// 向线程池中提交 6 个任务(每个任务:求 1-10 之和)
int sum = 0;
for (int j = 0; j <= 10; j++) {
sum += j;
}
return sum;
});
// 从 Future 中获取 result 的结果,这个方法是会被阻塞的,一直要等到线程任务返回结果
futureList.add(result);
}
for (Future<Integer> future : futureList) {
//获取并打印各个任务的结果
System.out.println(future.get());
}
pool.shutdown();
}
}
55
55
55
55
55
55
创作打卡挑战赛
赢取流量/现金/CSDN周边激励大奖
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/chengqiuming/article/details/124637151
内容来源于网络,如有侵权,请联系作者删除!