todo部分需要自行根据业务补偿补全
简介:
CountDownLatch用一个给定的计数器来初始化,该计数器的操作是原子操作,即同时只能有一个线程去操作该计数器。调用该类await方法的线程会一直处于阻塞状态,直到其他线程调用countDown方法使当前计数器的值变为零,每次调用countDown计数器的值减1。当计数器值减至零时,所有因调用await()方法而处于等待状态的线程就会继续往下执行。
package com.nineee.threadpool.countdownlatch;
import com.nineee.threadpool.BaseThreadPool;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class CountdownLatchDemo extends BaseThreadPool {
//业务并发数据数量
private static int count = 1000;
private static CountDownLatch countDownLatch = new CountDownLatch(count);
public static void main(String[] args) {
for(int i = 0; i < count; i++){
try {
executor.execute(() -> doService(countDownLatch,successCount));
}catch (Exception e){
e.printStackTrace();
//todo 任务因为并发太高执行拒绝策略,发生异常
countDownLatch.countDown();
}
}
try {
countDownLatch.await();
System.out.println("所有任务执行完毕");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("最终执行成功数量:"+successCount.get());
}
private static void doService(CountDownLatch countDownLatch, AtomicInteger successCount) {
//todo 业务逻辑
try{
System.out.println(Thread.currentThread().getName()+"线程执行任务");
successCount.incrementAndGet();
}catch (Exception e){
e.printStackTrace();
//todo 业务执行重试
}finally {
countDownLatch.countDown();
}
}
}
package com.nineee.threadpool;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
public class MyThreadFactory implements ThreadFactory {
static final AtomicInteger poolNumber = new AtomicInteger(1);
final ThreadGroup group;
final AtomicInteger threadNumber = new AtomicInteger(1);
final String namePrefix;
public MyThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null)? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
}
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon()) t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
package com.nineee.threadpool;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @Author: jingjiu.li
* @Date: 2020/7/9 14:49
* @Desc
*/
public class BaseThreadPool {
protected static AtomicInteger successCount;
protected static MyThreadFactory threadFactory;
protected static ThreadPoolExecutor.AbortPolicy abortPolicy;
protected static LinkedBlockingQueue taskQueues;
protected static ThreadPoolExecutor executor;
static {
successCount = new AtomicInteger(0);
threadFactory = new MyThreadFactory();
abortPolicy = new ThreadPoolExecutor.AbortPolicy();
taskQueues = new LinkedBlockingQueue<>(16);
executor = new ThreadPoolExecutor(8,
16,
2,
TimeUnit.SECONDS,
taskQueues,
threadFactory,
abortPolicy
);
}
}