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