JAVA线程池之newFixedThreadPool实战


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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM