网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
//空闲线程存活时间
private static final long keepAliveTime = 30000L;
static {
THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(corePoolSize,
maxPoolSize,
keepAliveTime,
TimeUnit.MICROSECONDS,
new LinkedBlockingQueue<>(workQueueCapacity),
//使用链式方法创建ThreadFactory
new ThreadFactoryBuilder().setNameFormat("my_definition_pool_").get(),
CallerRunsPolicy拒绝策略:在任务被拒绝添加到队列中后,会用调用execute函数的上层线程去执行被拒绝的任务。
new ThreadPoolExecutor.CallerRunsPolicy()) {
/**
* 处理线程池异常信息
*
* @param runnable
* @param throwable
*/
@Override
protected void afterExecute(Runnable runnable, Throwable throwable) {
super.afterExecute(runnable, throwable);
if (throwable == null && runnable instanceof Future<?>) {
try {
((Future<?>) runnable).get();
} catch (CancellationException ce) {
log.error("thread pool cancellation exception");
} catch (ExecutionException ee) {
log.error("thread pool execution exception");
} catch (InterruptedException ie) {
log.error("thread pool interrupted exception");
Thread.currentThread().interrupt();
}
if (throwable != null) {
log.error("thread pool exception");
}
}
}
};
//允许核心线程回收
THREAD_POOL_EXECUTOR.allowCoreThreadTimeOut(true);
}
public ThreadPoolExecutor getInstance() {
return THREAD_POOL_EXECUTOR;
}
}
测试类如下,
package com.hust.zhang;
import com.alibaba.fastjson.JSON;
import com.hust.zhang.threadpool.ThreadPool;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
@Slf4j
public class ThreadPoolTest {
static class ThreadProcess implements Runnable {
private int threadId;
private CountDownLatch countDownLatch;
ThreadProcess(int threadId, CountDownLatch countDownLatch) {
this.threadId = threadId;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
try {
MDC.put("threadId", String.valueOf(threadId));
} finally {
countDownLatch.countDown();
}
}
}
public static void main(String[] args) {
//通过ThreadPool枚举获取实例中的带有参数的线程池
ThreadPoolExecutor threadPool = ThreadPool.INSTANCE.getInstance();
int threadNum = 5;
CountDownLatch countDownLatch = new CountDownLatch(threadNum);
for (int i = 0; i < threadNum; i++) {
int threadId = i;
log.info("threadPool parameter:= {}", JSON.toJSONString(threadPool));
threadPool.submit(new ThreadProcess(threadId, countDownLatch));
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
log.info("throw InterruptedException");
}
System.out.println("mission accomplished!");
}
}
其中MDC可以用来记录线程的日志,方便在日志里通过grep命令追踪处理日志的线程。MDC通过MDCAdapter来实现,适配器有多种(BasicMDCAdapter、Log4jMDCAdapter、LogbackMDCAdapter、NOPMDCAdapter),主要是通过维护一个Map存与线程绑定的变量(ThreadLocal)。
上面是有限个任务放入到线程池中去,如果是无限个线程应该怎么做呢?下面针对可能会有无限个任务则放到队列中去,起一个线程循环判断队列是否为空,不为空则把任务放到线程池中。
package com.hust.zhang;
import com.hust.zhang.threadpool.ThreadPool;
import lombok.extern.slf4j.Slf4j;
import java.util.Arrays;
import java.util.Deque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Slf4j
public class ThreadPoolTest2 {
static class ThreadProcess implements Runnable {
private Deque deque;
ThreadProcess(Deque deque) {
this.deque = deque;
}
@Override
public void run() {
try {
Object value = deque.peek();
log.info("the task is running ... task value = {}", value);
} finally {
deque.poll();
}
}
}
public static void main(String[] args) {
Deque deque = MyLinkedDeque.getInstance();
ThreadPoolExecutor poolExecutor = ThreadPool.INSTANCE.getInstance();
poolExecutor.submit(() -> {
while (true) {
if (!deque.isEmpty()) {
poolExecutor.submit(new ThreadProcess(deque));
} else {
log.info("ConcurrentLinkedDeque is empty ...");
}
TimeUnit.SECONDS.sleep(1);
}
});
//启一个线程每隔5秒往队列中加三任务
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
TimeUnit.SECONDS.sleep(5);
Arrays.asList("task1","task2",123).stream().forEach(value -> deque.add(value));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
![img](https://img-blog.csdnimg.cn/img_convert/a206df916716a2de0b351b7c7d269f7f.png)
![img](https://img-blog.csdnimg.cn/img_convert/e7a157e0b77b4f5075003d16f6204ccb.png)
**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**
**[需要这份系统化的资料的朋友,可以添加戳这里获取](https://bbs.csdn.net/topics/618658159)**
**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**
,那么很难做到真正的技术提升。**
**[需要这份系统化的资料的朋友,可以添加戳这里获取](https://bbs.csdn.net/topics/618658159)**
**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**