以下是Executors
的默认线程工厂
static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
DefaultThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = “pool-” +
poolNumber.getAndIncrement() +
“-thread-”;
}
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;
}
}
线程池的拓展
在ThreadPoolExecutor中有三个扩展方法:
-
beforeExecute
:在任务执行前执行。 -
Execute
:任务执行后执行。 -
terminated
:线程池退出时执行。
在ThreadPoolExecutor中有一个内部类:Worker,每个线程的任务其实都是由这个类里面的run方法执行的。
private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable
{
/**
-
This class will never be serialized, but we provide a
-
serialVersionUID to suppress a javac warning.
*/
private static final long serialVersionUID = 6138294804551838833L;
/** Thread this worker is running in. Null if factory fails. */
final Thread thread;
/** Initial task to run. Possibly null. */
Runnable firstTask;
/** Per-thread task counter */
volatile long completedTasks;
// …省略
/** Delegates main run loop to outer runWorker */
public void run() {
runWorker(this);
}
// …省略
}
runWorker方法:
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
while (task != null || (task = getTask()) != null) {
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
// 任务执行前执行该方法
beforeExecute(wt, task);
Throwable thrown = null;
try {
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
// 任务执行后执行该方法
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
processWorkerExit(w, completedAbruptly);
}
}
还有一个线程池退出时执行的方法是在何处执行的?这个方法被调用的地方就不止一处了,像线程池的shutdown方法就会调用,例如ThreadPoolExecutor类的shutdown
方法:
public void shutdown() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
checkShutdownAccess();
advanceRunState(SHUTDOWN);
interruptIdleWorkers();
onShutdown(); // hook for ScheduledThreadPoolExecutor
} finally {
mainLock.unlock();
}
// 线程池退出时执行
tryTerminate();
}
ThreadPoolExecutor中这三个方法默认是没有任何内容的:
protected void beforeExecute(Thread t, Runnable r) { }
protected void afterExecute(Runnable r, Throwable t) { }
protected void terminated() { }
我们也可以自定义并重写他们,例如继承ThreadPoolExecutor
并重写这三个方法:
ExecutorService threadpool = new ThreadPoolExecutor(3, 10, 3L, TimeUnit.SECONDS,
new ArrayBlockingQueue(2)) {
@Override
protected void beforeExecute(Thread t, Runnable r) {
// 执行任务前
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
// 执行任务后
}
@Override
protected void terminated() {
// 线程退出
}
};
最后给出一个自己用的,开箱即用的线程池工具类:
package com.nobody.utils;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
-
线程池工具类
-
@author Μr.ηobοdy
-
@date 2020-05-20
*/
public class ThreadPoolUtils {
// 核心池大小
private static final int CORE_POOL_SIZE = 5;
// 线程池允许的最大线程数
private static final int MAXIMUM_POOL_SIZE = 10;
// 空闲的多余线程最大存活时间
private static final int KEEP_ALIVE_TIME = 3;
// 任务阻塞队列大小
private static final int QUEUE_SIZE = 3;
// 用于保存各个创建的线程池
private static Map<String, ThreadPoolExecutor> executorlist =
new ConcurrentHashMap<String, ThreadPoolExecutor>();
private static ThreadPoolExecutor getExecutor(String executorName) {
ThreadPoolExecutor executor = executorlist.get(executorName);
if (executor == null) {
synchronized (ThreadPoolUtils.class) {
if (executor == null) {
executor = create(executorName);
}
}
}
return executor;
}
// 使用特定线程池
public static void execute(String executorName, Runnable command) {
getExecutor(executorName).execute(command);
}
// 使用默认线程池
public static void execute(Runnable command) {
getExecutor(“DEFAULT”).execute(command);
}
// 使用特定线程池
public static Future submit(String executorName, Callable command) {
return getExecutor(executorName).submit(command);
}
// 使用默认线程池
public static Future submit(Callable command) {
return getExecutor(“DEFAULT”).submit(command);
}
// 如果executorlist中没有指定名称的线程池,则进行创建
private static ThreadPoolExecutor create(String executorName) {
ThreadPoolExecutor executor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE,
KEEP_ALIVE_TIME, TimeUnit.SECONDS, new ArrayBlockingQueue(QUEUE_SIZE),
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新
如果你觉得这些内容对你有帮助,可以添加V获取:vip1024b (备注Java)
复习的面试资料
这些面试全部出自大厂面试真题和面试合集当中,小编已经为大家整理完毕(PDF版)
- 第一部分:Java基础-中级-高级
- 第二部分:开源框架(SSM:Spring+SpringMVC+MyBatis)
- 第三部分:性能调优(JVM+MySQL+Tomcat)
- 第四部分:分布式(限流:ZK+Nginx;缓存:Redis+MongoDB+Memcached;通讯:MQ+kafka)
- 第五部分:微服务(SpringBoot+SpringCloud+Dubbo)
- 第六部分:其他:并发编程+设计模式+数据结构与算法+网络
进阶学习笔记pdf
- Java架构进阶之架构筑基篇(Java基础+并发编程+JVM+MySQL+Tomcat+网络+数据结构与算法)
- Java架构进阶之开源框架篇(设计模式+Spring+SpringMVC+MyBatis)
- Java架构进阶之分布式架构篇 (限流(ZK/Nginx)+缓存(Redis/MongoDB/Memcached)+通讯(MQ/kafka))
- Java架构进阶之微服务架构篇(RPC+SpringBoot+SpringCloud+Dubbo+K8s)
hH-1712026734142)]
- Java架构进阶之开源框架篇(设计模式+Spring+SpringMVC+MyBatis)
[外链图片转存中…(img-CBMzUWFy-1712026734142)]
[外链图片转存中…(img-j2eVuYCo-1712026734142)]
[外链图片转存中…(img-pN5chRkd-1712026734143)]
- Java架构进阶之分布式架构篇 (限流(ZK/Nginx)+缓存(Redis/MongoDB/Memcached)+通讯(MQ/kafka))
[外链图片转存中…(img-FbuRstcB-1712026734143)]
[外链图片转存中…(img-yDHTHUGp-1712026734143)]
[外链图片转存中…(img-GFoi5pud-1712026734144)]
- Java架构进阶之微服务架构篇(RPC+SpringBoot+SpringCloud+Dubbo+K8s)
[外链图片转存中…(img-c9RSZLg2-1712026734144)]
[外链图片转存中…(img-MFSDyzwp-1712026734144)]