自定義線程池 package com.appletree24; import java.util.ArrayDeque; import java.util.Deque; import java.util.HashSet; import java.util.concurrent.ExecutionEx ...
自定義線程池
package com.appletree24;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ThreadPool threadPool = new ThreadPool(2, 1000, TimeUnit.MICROSECONDS, 5, (queue, task) -> {
//帶超時等待
// queue.offer(task,500,TimeUnit.MILLISECONDS);
});
for (int i = 0; i < 10; i++) {
int j = i;
threadPool.execute(() -> {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(j);
});
}
}
}
//策略模式介面 此處使用策略模式是因為在實現拒絕策略時,有許多種拒絕的方式,這些方式如果不使用恰當的模式,就需要大量的if..else來編寫
//且方式數量大於4個,會造成類膨脹的問題,推薦使用混合模式
//https://www.runoob.com/design-pattern/strategy-pattern.html
@FunctionalInterface
interface RejectPolicy<T> {
void reject(BlockingQueue<T> queue, T task);
}
class ThreadPool {
//任務隊列
private BlockingQueue<Runnable> taskQueue;
//線程集合
private HashSet<Worker> workers = new HashSet<>();
//線程數
private int coreSize;
//超時時間
private long timeout;
private TimeUnit timeUnit;
private RejectPolicy<Runnable> rejectPolicy;
//執行任務
public void execute(Runnable task) {
//當任務數未超過核心線程數時,直接交給Worker對象執行
//如果超過,則加入阻塞任務隊列,暫存起來
synchronized (workers) {
if (workers.size() < coreSize) {
Worker worker = new Worker(task);
workers.add(worker);
worker.start();
} else {
//第一種選擇死等
// taskQueue.put(task);
//第二種為超時等待
//第三種為消費者放棄任務執行
//第四種為主線程拋出異常
//第五種讓調用者自行執行任務
taskQueue.tryPut(rejectPolicy, task);
}
}
}
public ThreadPool(int coreSize, long timeout, TimeUnit timeUnit, int queueCapcity, RejectPolicy<Runnable> rejectPolicy) {
this.coreSize = coreSize;
this.timeout = timeout;
this.timeUnit = timeUnit;
this.taskQueue = new BlockingQueue<>(queueCapcity);
this.rejectPolicy = rejectPolicy;
}
class Worker extends Thread {
private Runnable task;
public Worker(Runnable task) {
this.task = task;
}
@Override
public void run() {
//執行任務
//1.當傳遞過來的task不為空,執行任務
//2.當task執行完畢,再接著取下一個任務並執行
while (task != null || (task = taskQueue.poll(1000, TimeUnit.MILLISECONDS)) != null) {
try {
task.run();
} catch (Exception e) {
e.printStackTrace();
} finally {
task = null;
}
}
synchronized (workers) {
workers.remove(this);
}
}
}
}
class BlockingQueue<T> {
//1. 任務隊列
private final Deque<T> queue = new ArrayDeque<>();
//2. 鎖
private final ReentrantLock lock = new ReentrantLock();
//3. 生產者條件變數
private final Condition fullWaitSet = lock.newCondition();
//4. 消費者條件變數
private final Condition emptyWaitSet = lock.newCondition();
//5. 容量上限
private int capcity;
public BlockingQueue(int capcity) {
this.capcity = capcity;
}
//帶超時的等待獲取
public T poll(long timeout, TimeUnit unit) {
lock.lock();
long nanos = unit.toNanos(timeout);
try {
while (queue.isEmpty()) {
try {
if (nanos <= 0) {
return null;
}
nanos = emptyWaitSet.awaitNanos(nanos);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
T t = queue.removeFirst();
fullWaitSet.signal();
return t;
} finally {
lock.unlock();
}
}
//消費者拿取任務的方法
public T take() {
lock.lock();
try {
while (queue.isEmpty()) {
try {
emptyWaitSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
T t = queue.removeFirst();
fullWaitSet.signal();
return t;
} finally {
lock.unlock();
}
}
//阻塞添加
public void put(T task) {
lock.lock();
try {
while (queue.size() == capcity) {
try {
fullWaitSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.offerLast(task);
//添加完後喚醒消費者等待
emptyWaitSet.signal();
} finally {
lock.unlock();
}
}
//帶超時時間的阻塞添加
public boolean offer(T task, long timeout, TimeUnit unit) {
lock.lock();
try {
long nanos = unit.toNanos(timeout);
while (queue.size() == capcity) {
try {
if (nanos <= 0) return false;
nanos = fullWaitSet.awaitNanos(nanos);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.offerLast(task);
//添加完後喚醒消費者等待
emptyWaitSet.signal();
return true;
} finally {
lock.unlock();
}
}
//獲取當前阻塞隊列大小
public int size() {
lock.lock();
try {
return queue.size();
} finally {
lock.unlock();
}
}
public void tryPut(RejectPolicy<T> rejectPolicy, T task) {
lock.lock();
try {
//判斷隊列是否已滿
if (queue.size() == capcity) {
rejectPolicy.reject(this, task);
} else {
queue.addLast(task);
emptyWaitSet.signal();
}
} finally {
lock.unlock();
}
}
}
上述的自定義線程池雖然能夠執行完畢主線程給予的任務,但任務全部執行結束後,開闢的線程池內核心線程仍然在運行,並沒有結束,這是因為目前線程池中的take方法仍然為不會有超時等待的take方法,造成了死等,需要為其加入超時停止的功能。也就是替代take()的poll()
JDK自帶線程池
介紹
ThreadPoolExecutor使用int的高三位表示線程池狀態,低29位表示線程數量
在ThreadPoolExecutor中,同樣也存在拒絕策略。其圖結構如下:
其中介面就對應著在自定義線程池中實現的策略模式介面,下麵的四個實現類就對應著四種不同的拒絕方式:
利用工具類創建固定大小線程池
利用工具類創建帶緩衝的線程池
從源碼可以看出,帶緩衝的線程池中緩衝隊列的使用的是一個名為SynchronousQueue
的隊列,這個隊列的特點如下:隊列不具有容量,當沒有線程來取時,是無法對其內部放入數據的,例如隊列內部已有一個數字1,但此時沒有線程取走,則線此隊列目前並不能繼續存入數據,直到1被取走
利用工具類創建單線程線程池
從源碼可以看出,單線程線程池中核心線程數與最大線程數相等,即不存在應急線程。只能解決一個任務
那麼這個線程池和我自己創建一個線程的線程池有什麼區別呢?區別如下:
ThreadPoolExecutor-submit method
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(2);
Future<String> result = pool.submit(() -> {
System.out.println("running");
Thread.sleep(1000);
return "ok";
});
System.out.println(result.get());
}
submit方法可以傳入Runnable和Callable類型的參數,並且將線程內部所執行任務的結果返回,用Future包裝
ThreadPoolExecutor-invokeAll
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(2);
List<Future<String>> results = pool.invokeAll(Arrays.asList(() -> {
System.out.println("begin");
Thread.sleep(1000);
return "1";
},
() -> {
System.out.println("begin");
Thread.sleep(500);
return "2";
}));
results.forEach(f -> {
try {
System.out.printf(f.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
}
invokeAll方法可以傳入任務的集合,同樣的任務的返回值也會以列表形式返回
ThreadPoolExecutor-invokeAny
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(2);
String result = pool.invokeAny(Arrays.asList(() -> {
System.out.println("begin");
Thread.sleep(1000);
return "1";
},
() -> {
System.out.println("begin");
Thread.sleep(500);
return "2";
}));
pool.awaitTermination(1000, TimeUnit.MILLISECONDS);
System.out.println(result);
}
invokeAny方法同樣可以傳入任務的集合,只不過最後返回的結果並不是任務的結果集合,而是最早完成的那個任務的結果。
ThreadPoolExecutor-shutdown
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(2);
List<Future<String>> results = pool.invokeAll(Arrays.asList(() -> {
System.out.println("begin");
Thread.sleep(1000);
return "1";
},
() -> {
System.out.println("begin");
Thread.sleep(500);
return "2";
}));
pool.shutdown();
results.forEach(f -> {
try {
System.out.println(f.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
}
shutdown方法會將線程池的狀態變為SHUTDOWN
- 不會接受新任務
- 但已提交的任務會執行完
- 此方法不會阻塞調用線程的執行
ThreadPoolExecutor-shutdownNow
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(2);
List<Future<String>> results = pool.invokeAll(Arrays.asList(() -> {
System.out.println("begin");
Thread.sleep(1000);
return "1";
},
() -> {
System.out.println("begin");
Thread.sleep(500);
return "2";
}));
List<Runnable> runnables = pool.shutdownNow();
results.forEach(f -> {
try {
System.out.println(f.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
}
shutdownNow方法會將線程池狀態變為STOP
- 不會接受新任務
- 會將隊列中現有的任務返回
- 並且用interrupt方法中斷正在執行的任務