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