FixedThreadPool使用demo

Posted jsliao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了FixedThreadPool使用demo相关的知识,希望对你有一定的参考价值。

FixedThreadPool使用demo

package test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class FixedThreadPoolTest {
// 定长线程池
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
/**
* 超时时间/分钟
*/
public static final int TIMEOUT = 5;

public void testFixedThreadPool() {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> map1 = new HashMap<String, String>();
map1.put("applNo", "666");
list.add(map1);
Map<String, String> map2 = new HashMap<String, String>();
map2.put("applNo", "667");
list.add(map2);
Map<String, String> map3 = new HashMap<String, String>();
map3.put("applNo", "668");
list.add(map3);
List<Callable<Boolean>> callableList = new ArrayList<Callable<Boolean>>();
if (list.size() > 0) {
System.out.println("执行次数:" + list.size());
for (final Map map : list) {
Callable<Boolean> call = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
try {
return doYouMethod();
} catch (Exception e) {
System.out.println("执行异常:" + e);
return null;
}
}
};
callableList.add(call);
}
}

try {
List<Future<Boolean>> futureList = fixedThreadPool.invokeAll(callableList);
for (Future<Boolean> future : futureList) {
Boolean flag = future.get(TIMEOUT, TimeUnit.MINUTES);
if (flag) {
System.out.println(" 成功");
} else {
System.out.println(" 失败");
}
}

} catch (Exception e) {
System.out.println(" ----- 异常 -----" + e.getMessage());
}
}

public Boolean doYouMethod() {
System.out.println(Thread.currentThread().getName());
System.out.println("执行你的方法");
return true;
}

public static void main(String[] args) {
FixedThreadPoolTest ft = new FixedThreadPoolTest();
ft.testFixedThreadPool();
}
}

































































以上是关于FixedThreadPool使用demo的主要内容,如果未能解决你的问题,请参考以下文章

如何选择FixedThreadPool和CachedThreadPool

Java 线程池之FixedThreadPool(Java代码实战-003)

Executor FixedThreadPool 执行后会发生啥,因为 executor 没有关闭方法?

基础线程机制

Dubbo中的线程池——自适应扩展点应用之一

阿里为何不允许用Executors创建线程池?