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