java的多线程推荐使用ThreadPoolExecutor来创建和使用线程池,废话不多说:
package com.zhh;
import java.util.concurrent.*;
/**
* @Author: zhh
* @Date: 2019/11/11 15:20
* @Description: This is an example of ThreadPoolExecutor usage.
*/
public class TestThreadPool {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = getExecutorService();
Future<String> f1 = submitTask(executorService, new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("Thread 1 is running……");
Thread.sleep(5000); //睡5秒
return "1 done!";
}
});
Future<String> f2 = submitTask(executorService, new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("Thread 2 is running……");
Thread.sleep(5000); //睡5秒
return "2 done!";
}
});
Future<String> f3 = submitTask(executorService, new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("Thread 3 is running……");
Thread.sleep(5000); //睡5秒
return "3 done!";
}
});
Future<String> f4 = submitTask(executorService, new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("Thread 4 is running……");
Thread.sleep(5000); //睡5秒
return "4 done!";
}
});
Future<String> f5 = submitTask(executorService, new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("Thread 5 is running……");
Thread.sleep(5000); //睡5秒
return "5 done!";
}
});
Future<String> f6 = submitTask(executorService, new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("Thread 6 is running……");
Thread.sleep(5000); //睡5秒
return "6 done!";
}
});
System.out.println(f1.get());
System.out.println(f2.get());
System.out.println(f3.get());
System.out.println(f3.get());
System.out.println(f5.get());
}
/**
* 必须要自行处理提交异常,否则线程执行会中断,即使提交成功也无法继续执行
* @param executorService
* @param callable
* @return
*/
public static Future<String> submitTask(ExecutorService executorService, Callable<String> callable){
try{
Future<String> f = executorService.submit(callable);
return f;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public static ExecutorService getExecutorService(){
int poolSize = Runtime.getRuntime().availableProcessors();
System.out.println(poolSize);
//超出队列的size,再继续添加任务,会直接根据RejectedExecutionHandler来决定处理新任务的策略
//AbortPolicy : 对于超出队列大小后面再添加的任务直接抛异常
//DiscardPolicy : 什么也不做,直接忽略
BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1);
RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
ExecutorService executorService = new ThreadPoolExecutor(poolSize, poolSize,
0, TimeUnit.SECONDS, queue, handler);
return executorService;
}
}