JAVA线程池之newFixedThreadPool实战

2019-01-16 05:51:28来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

JAVA线程池之newFixedThreadPool实战

1.线程池分类:

FixThreadPool 定长线程池,CachedThreadPool 缓存线程池,ScheduledThreadPool 定时线程池,SingleThreadPool单线程的线程池

下面创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。示例代码如下:

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();
}
}

 


原文链接:https://www.cnblogs.com/jsliao/p/10273549.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:java后端通过Filter过滤器解决跨域问题

下一篇:Eclipse常用20个快捷键