J.U.C & JVM
2021-12-06 23:18:21 42 举报
cloudman
作者其他创作
大纲/内容
AbstractQueuedSynchronizer
ExecutorService 接口
ReentrantLock
private final Sync sync;abstract static class Sync extends AbstractQueuedSynchronizer { ......}static final class NonfairSync extends Sync { ......}static final class FairSync extends Sync { ......}public ReentrantLock(boolean fair); 初始化时确定使用公平锁还是非公平锁void lock();void unlock();boolean tryLock();public final boolean isFair()
Blocked
load
Y
按饱和策略 处理无法执行的任务
N
Runnable包括 \"运行\"和\"就绪\"
抢到锁
read
New
运行中
创建线程执行任务
ReadWriteLock 接口
Lock readLock();Lock writeLock();
notify()notifyAll()
assign
Executor 接口
void execute(Runnable command);
执行完
超出最大线程数?
Terminated
主内存
ThreadLocalMap
store
超出核心线程数?
线程池运行机制
use
Lock 锁组件
这两个状态的区别就是:Waiting 直到被其它线程唤醒才会回到Runnable状态;TimedWaiting 在等待了设置的时间后,自动进入Runnable状态
线程状态转换图
Executors 线程池工具类
public static ExecutorService newFixedThreadPool(int nThreads);public static ExecutorService newSingleThreadExecutor();public static ExecutorService newCachedThreadPool();
TimedWaiting
notify()notifyAll()等待超时
等待获取锁
Waiting
ThreadPoolExecutor
private final BlockingQueue<Runnable> workQueue;private volatile ThreadFactory threadFactory;private volatile int corePoolSize;private volatile int maximumPoolSize;public void execute(Runnable command);
1、每个Thread对象都持有一个ThreadLocalMap对象;2、当调用一个ThreadLocal的set方法时,先得到当前线程的ThreadLocalMap对象,然后将<ThreadLocal,value>键值对插入到该Map中
工作内存A
系统
调度
Thread1
抢到时间片就“运行”,抢不到就“就绪”
提交任务
就绪
Thread2
AbstractExecutorService
从上面继承等待 submit()、execute() 等方法
线程A
Lock 接口
void lock();void unlock();boolean tryLock();
write
工作队列已满?
sleep(long)wait(long)join(long)
任务添加到队列,等待执行
ReentrantReadWriteLock
private final ReentrantReadWriteLock.ReadLock readerLock;private final ReentrantReadWriteLock.WriteLock writerLock;final Sync sync;abstract static class Sync extends AbstractQueuedSynchronizer { ......}static final class NonfairSync extends Sync { ......}static final class FairSync extends Sync { ......}public static class ReadLock implements Lock { ......}public static class WriteLock implements Lock { ......}public ReentrantReadWriteLock(boolean fair);初始化时确定:实例化非公平读写锁,还是公平读写锁public ReentrantReadWriteLock.WriteLock writeLock();public ReentrantReadWriteLock.ReadLock readLock()public final boolean isFair();
Executor 线程池组件
wait()join()
收藏
0 条评论
下一页