1、自定义线程池
package com.sharing_model.ThreadPool;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* 自定义线程池
*/
public class TestPool {
public static void main(String[] args) {
ThreadPool threadPool =
new ThreadPool(1, 1000,TimeUnit.MILLISECONDS, 1, (queue, task) -> {
//拒绝策略:
//1.死等
// queue.put(task);
//2.超时等待
// queue.offer(task, 500, TimeUnit.MILLISECONDS);
//3.让调用者放弃任务执行
// System.out.println("放弃任务");
//4.让调用者抛出异常
// throw new RuntimeException("任务执行失败" + task);
//5.让调用者自己执行任务
// task.run();
});
for (int i = 0; i < 15; i++) {
int j = i;
threadPool.execute(() -> {
try {
Thread.sleep(1000 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(j);
});
}
}
}
@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) {
//当任务数没有超过coreSize时,直接交给worker对象执行
//如果任务数超过coreSize时,加入任务队列暂存
synchronized (workers) {
if (workers.size() < coreSize) {
System.out.println("新增worker" + workers);
Worker worker = new Worker(task);
workers.add(worker);
worker.start();
} else {
System.out.println("加入任务队列" + task);
//taskQueue.put(task);
//拒绝策略:1)死等 2)带超时等待 3)放弃任务执行 4)让调用者抛出异常 5)让调用者自己执行任务
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(timeout, timeUnit)) != null) {
try {
System.out.println("正在执行" + task);
task.run();
} catch (Exception e) {
e.printStackTrace();
} finally {
task = null;
}
}
synchronized (workers) {
System.out.println("worker被移除" + this);
workers.remove(this);
}
}
}
}
//阻塞队列:放任务的,线程从阻塞队列拿任务执行
class BlockingQueue<T> {
//1、任务队列
private Deque<T> queue = new ArrayDeque<>();
//2、锁
private ReentrantLock lock = new ReentrantLock();
//3、生产者条件变量
private Condition fullWaitSet = lock.newCondition();
//4、消费者条件变量
private Condition emptyWaitSet = lock.newCondition();
//5、容量
private int capcity;
public BlockingQueue(int capcity) {
this.capcity = capcity;
}
//带超时的阻塞获取
public T poll(long timeout, TimeUnit unit) {
lock.lock();
try {
//将timeout统一转换为纳秒
long nanos = unit.toNanos(timeout);
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 {
System.out.println("等待加入任务队列" +task);
fullWaitSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("加入任务队列" + task);
queue.addLast(task);
emptyWaitSet.signal();
} finally {
lock.unlock();
}
}
//带超时的阻塞添加
public boolean offer(T task, long timeout, TimeUnit timeUnit) {
lock.lock();
try {
long nanos = timeUnit.toNanos(timeout);
while (queue.size() == capcity) {
try {
System.out.println("等待加入任务队列" +task);
nanos = fullWaitSet.awaitNanos(nanos);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("加入任务队列" + task);
queue.addLast(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 {//有空闲
System.out.println("加入任务队列" + task);
}
} finally {
lock.unlock();
}
}
}
2、ThreadPoolExecutor
1)线程池状态
ThreadPoolExecutor 使用int的高3位来表示线程池状态,低29表示线程数量
从数字上来比较,TERMINATED > TIDYING > STOP > SHUTDOWN > RUNNING (首位表示的是符号位,所以RUNNING最小)
这些信息存储在一个原子变量ctl中,目的是将线程状态和线程个数合二为一,这样就可以使用一次cas原子操作进行赋值
//c为旧值 ,ctlof返回结果为新值
ctl.compareAndSet(c, ctlOf(targerState, workerCountOf(c)));
//rs 为高3位代表线程池状态,wc为低29位代表线程个数,ctl是合并他们
private static int ctlOf(int rs, int wc) { return rs | wc; }
2)构造方法
public ThreadPoolExecutor(
int corePoolSize, //核心线程数
int maximumPoolSize,//最大线程数目(核心线程数 + 急救线程数)
long keepAliveTime, //生存时间-针对救急线程
TimeUnit unit, //时间单位-针对救急线程
BlockingQueue<Runnable> workQueue, //阻塞队列
ThreadFactory threadFactory,//线程工厂-可以为线程创建时起一个好名字
RejectedExecutionHandler handler //拒绝策略
)
3、newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
4、newCachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronizedQueue<Runnable>());
}
5、newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor {
return new FinalizableDelegatedExecutorService (
new ThreadPoolExecutor(1, 1 0L, TimeUnit.MILLISECONDS, new LinkedBlockQueue<Runnbale> ();
)
}
6、提交任务
package com.sharing_model.ThreadPool;
import java.util.concurrent.*;
/**
* submit:使用了保护性暂停模式
*/
public class SubmitTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(2);
//可以使用lambda来进行简化 alt + enter
Future<String> future = pool.submit(new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("running");
Thread.sleep(1000);
return "ok";
}
});
System.out.println(future.get());
}
}
package com.sharing_model.ThreadPool;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* invokeAll
*/
public class InvokeAllTest {
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(2);
List<Future<String>> futures = pool.invokeAll(Arrays.asList(
() -> {
System.out.println("begin");
Thread.sleep(1000);
return "1";
},
() -> {
System.out.println("begin");
Thread.sleep(500);
return "2";
},
() -> {
System.out.println("begin");
Thread.sleep(2000);
return "3";
}
));
futures.forEach(f -> {
try {
System.out.println(f.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
});
}
}
package com.sharing_model.ThreadPool;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* invokeAny
*/
public class InvokeAnyTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(1);
String result = pool.invokeAny(Arrays.asList(
() -> {
System.out.println("begin");
Thread.sleep(1000);
return "1";
},
() -> {
System.out.println("begin");
Thread.sleep(500);
return "2";
},
() -> {
System.out.println("begin");
Thread.sleep(2000);
return "3";
}
));
System.out.println(result);
}
}
7、关闭线程池
shutdown
/**
* 线程状态变为SHUTDOWN
* -不会接收新任务
* -但已提交任务会执行完
* -此方法不会阻塞调用线程的执行
*/
void shutdown();
shutdownNow
/**
*线程池状态变为STOP
*-不会接受新任务
*-会将队列中的任务返回
*-并且interrup的方式中断正在执行的任务
*/
List<Runnable> shutdownNow();
其它方法
//不在UNNING状态的线程池,此方法就返回true
boolean isShutdown();
//线程池状态是否是 TERMINATED
boolean isTerminated()
//调用shutdown后,由于调用线程并不会等待所有任务运行结,因此如果它想在线程池TERMINATED后做一些事
//情,可以利用此方法等待
boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;