cn.sanenen.sunutils.thread.AsyncBlockedThreadPoolExecutor Maven / Gradle / Ivy
package cn.sanenen.sunutils.thread;
import cn.hutool.log.Log;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.util.concurrent.ListenableFutureTask;
import java.util.concurrent.*;
/**
* "@async"使用阻塞式线程池 方法不可以有返回值
* 使用方法:
*
* @Bean public AsyncTaskExecutor taskExecutor(){
* AsyncBlockedThreadPoolExecutor executor = new AsyncBlockedThreadPoolExecutor(线程数量);
* executor.setThreadNamePrefix("asyncBlocked");
* return executor;
* }
*/
public class AsyncBlockedThreadPoolExecutor extends ThreadPoolTaskExecutor {
private static final Log log = Log.get();
private final Semaphore semaphore;
public AsyncBlockedThreadPoolExecutor(int poolSize) {
super.setCorePoolSize(poolSize);
semaphore = new Semaphore(poolSize);
}
@Override
public Future submit(Callable task) {
try {
semaphore.acquire();
ListenableFutureTask listenableFutureTask = new ListenableFutureTask<>(task);
listenableFutureTask.addCallback(new ListenableFutureCallback