package com.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.validation.constraints.NotNull;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Test {
private static final Logger logger = LoggerFactory.getLogger(Test.class);
/**
* ThreadPoolExecutor 底层workQueue调用的offer来入队.offer不会block,这里改成put,当队列满时可阻塞住submit
*/
public static ExecutorService newFixedThreadPool(int nThreads, int capacity) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new OfferBlockingQueue<>(capacity));
}
private static final class OfferBlockingQueue<E> extends LinkedBlockingQueue<E> {
public OfferBlockingQueue(int capacity) {
super(capacity);
}
@Override
public boolean offer(@NotNull E e) {
try {
put(e);
return true;
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
return false;
}
}
}
public static void main(String[] args) throws InterruptedException {
ExecutorService fixedThreadPool1 = newFixedThreadPool(2, 4);
for (int i = 0; i < 8; i++) {
int temp = i;
logger.info("temp: " + temp);
fixedThreadPool1.submit(() -> {
try {
logger.info("start temp: " + temp);
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
logger.info("end temp: " + temp);
}
});
}
logger.info("等待线程池[fixedThreadPool1]执行任务");
fixedThreadPool1.shutdown();
while (!fixedThreadPool1.awaitTermination(5, TimeUnit.SECONDS)) {
logger.info("线程池[fixedThreadPool1]执行任务中...");
}
logger.info("线程池[fixedThreadPool1]执行任务完成");
}
}
带阻塞功能的线程池
最新推荐文章于 2023-08-14 21:49:18 发布