有3个实体分别是:AsyncSetterFactory、TestEntity、AsyncSetter
AsyncSetter:
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
public class AsyncSetter<T> {
private static Logger log = LoggerFactory.getLogger(AsyncSetter.class);
List<Consumer<T>> consumers = new ArrayList<>();
private Executor executor;
private T original;
private int timeout;
AsyncSetter(Executor executor, int timeout) {
this.executor = executor;
this.timeout = timeout;
}
public AsyncSetter<T> setOriginal(T original) {
this.original = original;
return this;
}
public AsyncSetter<T> addRunnable(Consumer<T> c) {
consumers.add(c);
return this;
}
public void execute() {
CountDownLatch countDownLatch = new CountDownLatch(consumers.size());
for (Consumer c : consumers) {
executor.execute(() -> {
try {
c.accept(original);
} catch (Exception e) {
log.error("执行线程失败:{}", ExceptionUtils.getFullStackTrace(e));
} finally {
countDownLatch.countDown();
}
});
}
monitoringLog();
boolean await = false;
try {
await = countDownLatch.await(timeout, TimeUnit.SECONDS);
log.info("AsyncSetter[{}]执行结束", this.hashCode());
if (!await)
log.info("AsyncSetter[{}]执行未完成", this.hashCode());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private void monitoringLog() {
ObjectMapper mapper = new ObjectMapper();
ObjectNode objectNode = mapper.createObjectNode();
ThreadPoolExecutor threadPoolExecutor = ((ThreadPoolTaskExecutor) this.executor).getThreadPoolExecutor();
objectNode.put("PoolSize", threadPoolExecutor.getPoolSize());
objectNode.put("CompletedTaskCount", threadPoolExecutor.getCompletedTaskCount());
objectNode.put("LargestPoolSize", threadPoolExecutor.getLargestPoolSize());
objectNode.put("TaskCount", threadPoolExecutor.getTaskCount());
log.debug(JSON.toJSONString(objectNode));
}
public T getOriginal() {
return original;
}
}
AsyncSetterFactory:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.Executor;
public class AsyncSetterFactory {
private Executor executor;
private int timeout;
private Logger log = LoggerFactory.getLogger(AsyncSetterFactory.class);
public AsyncSetterFactory (Executor executor, int timeout){
this.executor = executor;
this.timeout = timeout;
log.debug("AsyncSetter的timeout值为{}", this.timeout);
}
public AsyncSetter getAsyncSetter(){
return new AsyncSetter(executor, timeout);
}
}
TestEntity:
import java.io.Serializable;
public class TestEntity implements Serializable{
private static final long serialVersionUID = -7328012686479874469L;
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
下面是具体的实现过程:
import java.util.Date;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
public class TestCountDownLatch {
public static void main(String[] args) {
//创建线程池
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(200);
executor.setMaxPoolSize(600);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("asyncSetter-executor-");
executor.initialize();
//首先创建出CountDownLatch工厂 AsyncSetterFactory
AsyncSetterFactory asyncSetterFactory = new AsyncSetterFactory(executor,10);
Long current = System.currentTimeMillis();
AsyncSetter<TestEntity> asyncSetter = asyncSetterFactory.getAsyncSetter();
asyncSetter.setOriginal(new TestEntity()).
addRunnable(vo ->funtion1(vo)).
addRunnable(vo ->funtion2(vo)).execute();
TestEntity original = asyncSetter.getOriginal();
System.out.println("name:" + original.getName() + ",age:" + original.getAge());
System.out.println("共执行了" + (new Date().getTime() - current) + "ms");
System.out.println("不用多线程===============");
Long current2 = System.currentTimeMillis();
TestEntity testEntity = new TestEntity();
funtion1(testEntity);
funtion2(testEntity);
System.out.println("不用多线程===============name:" + original.getName() + ",age:" + original.getAge());
System.out.println("不用多线程===============共执行了" + (new Date().getTime() - current2) + "ms");
}
public static void funtion1(TestEntity entity){
try {
System.out.println("funtion1当前线程" + Thread.currentThread().getName());
Thread.currentThread().sleep(3000);
entity.setName("张三");
} catch (Exception e) {
}
}
public static void funtion2(TestEntity entity){
try {
System.out.println("funtion2当前线程" + Thread.currentThread().getName());
Thread.currentThread().sleep(3000);
entity.setAge("李四");
} catch (Exception e) {
}
}
}