线程池管理
package com.zfinfo;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
public class MyExecutor {
private ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1);
private List<Future> futureList = new Vector<>();
public void submit(List<String> list) {
for (String str : list) {
futureList.add(executor.submit(new MyCallable().init(str)));
}
}
public int getActiveCount(){
return ((ThreadPoolExecutor)executor).getActiveCount();
}
public void shutdown() {
executor.shutdown();
}
public List<Future> getFutureList() {
return futureList;
}
public ExecutorService getExecutor() {
return executor;
}
public MyExecutor setThreads(int threads) {
this.executor = Executors.newFixedThreadPool(threads);
return this;
}
}
有返回值的线程Callable接口的实现
package com.zfinfo;
import java.util.concurrent.Callable;
public class MyCallable implements Callable<Object> {
private String str;
public MyCallable init(String str) {
this.str = str;
return this;
}
@Override
public Object call() throws Exception {
return "call:" + str;
}
}
测试
public static void main(String[] args) throws Exception {
List<String> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
list.add(UUID.randomUUID().toString());
}
MyExecutor myExecutor = new MyExecutor();
myExecutor.submit(list);
List<Future> futureList = myExecutor.getFutureList();
for (int i = 0; i < futureList.size(); i++) {
System.out.println(i + ":" + futureList.get(i).get());
}
myExecutor.shutdown();
System.out.println("availableProcessors:"+Runtime.getRuntime().availableProcessors());
System.out.println("totalMemory:"+Runtime.getRuntime().totalMemory());
System.out.println("freeMemory:"+Runtime.getRuntime().freeMemory());
System.out.println("maxMemory:"+Runtime.getRuntime().maxMemory());
}
结果
0:call:b49d2006-8a91-4217-8f17-db2349448897
1:call:548dba0a-0ccc-4a1f-b897-bf30c3da54c3
2:call:00b02d86-31ef-4b5b-890d-471397eef636
3:call:3c9f683f-43a8-4451-ac61-70bac41d8d7e
4:call:4b18a89f-4050-4019-a78f-e481637748da
availableProcessors:4
totalMemory:56623104
freeMemory:52973240
maxMemory:826277888