import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 符合阿里巴巴规范的线程池
*/
public class ThreadPoolUtil {
public static ThreadPoolExecutor threadPool;
//无返回值
public static void execute(Runnable runnable){
getThreadPool().execute(runnable);
}
// 有返回值
public static <T> Future<T> submit(Callable<T> callable){
return getThreadPool().submit(callable);
}
//线程池对象
public static ThreadPoolExecutor getThreadPool() {
if (threadPool != null) {
return threadPool;
} else {
synchronized (ThreadPoolUtil.class) {
if (threadPool == null) {
threadPool = new ThreadPoolExecutor(8, 16, 60, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(32), new ThreadPoolExecutor.CallerRunsPolicy());
}
return threadPool;
}
}
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class Furture {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//方式1 无返回值
ThreadPoolUtil.execute(new Runnable() {
@Override
public void run() {
}
});
//方式2 有返回值
long start = System.currentTimeMillis();
List<Future> futureList = new ArrayList();
try {
Future<String> messageFuture = ThreadPoolUtil.submit(new Callable<String>() {
@Override
public String call() throws Exception {
return "OK";
}
});
futureList.add(messageFuture);
} catch (Exception e) {
e.printStackTrace();
}
for (Future<String> message : futureList) {
String messageData = message.get();
System.out.println(messageData);
}
System.out.println(String.format("耗时%s毫秒", System.currentTimeMillis() - start));
}
}