自定义线程池
@Slf4j(topic = "PoolTest")
public class PoolTest {
public static void main(String[] args) {
ThreadPool threadPool = new ThreadPool(2, 1000L, TimeUnit.SECONDS, 10);
for (int i = 0; i < 5; i++) {
int j = i;
threadPool.execute(()->{
log.debug("当前线程{}",j);
});
}
}
}
@Slf4j(topic = "ThreadPool")
class ThreadPool{
private BlockingQueue<Runnable> taskQueue;
private HashSet<Worker> workers = new HashSet<>();
private int coreSize;
private Long timeOut;
private TimeUnit timeUnit;
public ThreadPool(int coreSize, Long timeOut, TimeUnit timeUnit,int QueueSize) {
this.coreSize = coreSize;
this.timeOut = timeOut;
this.timeUnit = timeUnit;
this.taskQueue = new BlockingQueue<>(QueueSize);
}
public void execute(Runnable runnable){
synchronized (workers){
if (workers.size()<coreSize) {
Worker worker = new Worker(runnable);
log.debug("添加执行线程{}",runnable);
workers.add(worker);
worker.start();
}else{
log.debug("等待执行线程{}",runnable);
taskQueue.put(runnable);
}
}
}
class Worker extends Thread{
private Runnable task;
public Worker(Runnable runnable){
this.task = runnable;
}
@Override
public void run() {
while (task != null || (task = taskQueue.poll(1000L,TimeUnit.SECONDS)) != null) {
try {
log.debug("执行当前线程{}",task);
task.run();
}catch (Exception e){
e.printStackTrace();
}finally {
task = null;
}
}
synchronized (workers){
log.debug("移除当前线程{}",task);
workers.remove(this);
}
}
}
}
class BlockingQueue<T>{
public BlockingQueue(int cacheSize) {
this.cacheSize = cacheSize;
}
private Deque<T> queue = new ArrayDeque<>();
private ReentrantLock lock = new ReentrantLock();
private Condition fullWaitSet = lock.newCondition();
private Condition emptyWaitSet = lock.newCondition();
private int cacheSize;
@SneakyThrows
public T poll(Long timeOut, TimeUnit unit){
lock.lock();
try {
long nanos = unit.toNanos(timeOut);
while (queue.isEmpty()){
if (nanos <= 0){
return null;
}
nanos = emptyWaitSet.awaitNanos(nanos);
}
T t = queue.removeFirst();
fullWaitSet.signal();
return t;
}finally {
lock.unlock();
}
}
@SneakyThrows
public T task(){
lock.lock();
try {
while (queue.isEmpty()){
emptyWaitSet.await();
}
T t = queue.removeFirst();
fullWaitSet.signal();
return t;
}finally {
lock.unlock();
}
}
@SneakyThrows
public void put(T t){
lock.lock();
try {
while (queue.size() == cacheSize){
fullWaitSet.await();
}
queue.add(t);
emptyWaitSet.signal();
}finally {
lock.unlock();
}
}
@SneakyThrows
public boolean offset(T t,Long timeOut,TimeUnit timeUnit){
lock.lock();
try {
long nanos = timeUnit.toNanos(timeOut);
while (queue.size() == cacheSize){
if (nanos <= 0){
return false;
}
nanos = fullWaitSet.awaitNanos(nanos);
}
queue.add(t);
emptyWaitSet.signal();
return true;
}finally {
lock.unlock();
}
}
public int size(){
lock.lock();
try {
return queue.size();
}finally {
lock.unlock();
}
}
}
线程池的状态和线程池的拒绝策略
线程池的状态
JDK线程池的 拒绝策略
1、AbortPolicy 让调用者抛出RejectedExecutionException异常 默认策略
2、CallerRunsPolicy 让调用者运行任务
3、DiscardPolicy 放弃本次任务
4、DiscardOldestPolicy 放弃队列中最早的任务,让本任务取而代之
创建线程池
new ThreadPoolExecutor(2,3,1000L, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
固定线程数的线程池
@Slf4j(topic = "ThreadPoolExecutorsTest")
public class ThreadPoolExecutorsTest {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2, new ThreadFactory() {
private AtomicInteger t = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
return new Thread(r,"MyPool_t" + t.getAndIncrement());
}
});
pool.execute(()->{
log.debug("1");
});
pool.execute(()->{
log.debug("2");
});
pool.execute(()->{
log.debug("3");
});
pool.shutdown();
}
}
缓存线程池的创建
public class CacheThreadPoolTest {
public static void main(String[] args) {
ExecutorService pool = Executors.newCachedThreadPool();
}
}
单例线程池的创建
@Slf4j(topic = "SingleThreadExecutorTest")
public class SingleThreadExecutorTest {
public static void main(String[] args) {
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(()->{
log.debug("1");
int i = 1 /0;
});
service.execute(()->{
log.debug("2");
});
service.execute(()->{
log.debug("3");
});
}
}
线程池的api
@Slf4j(topic = "TestPool")
public class TestPool {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(2);
Future<String> future = pool.submit(() -> {
log.debug("有返回的线程执行");
return "OK";
});
log.debug("{}",future.get());
List<Future<String>> list = pool.invokeAll(Arrays.asList(
() -> {
log.debug("1");
Thread.sleep(1000L);
return "1";
},
() -> {
log.debug("1");
Thread.sleep(1500L);
return "2";
},
() -> {
log.debug("1");
Thread.sleep(2000L);
return "3";
}
));
list.forEach(s -> {
try {
log.debug("{}",s.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
String result = pool.invokeAny(Arrays.asList(
() -> {
log.debug("invokeAny1");
Thread.sleep(1000L);
return "invokeAny1";
},
() -> {
log.debug("invokeAny2");
Thread.sleep(1500L);
return "invokeAny2";
},
() -> {
log.debug("invokeAny3");
Thread.sleep(2000L);
return "invokeAny3";
}
));
log.debug("{}",result);
}
}