一,Condition 一个场景,两个线程数数,同时启动两个线程,线程A数1.2.3,然后线程B数4.5.6,最后线程A数7.8.9,程序结束,这涉及到线程之间的通信. public class ConditionTest { static class NumberWrapper { public int value = 1; } public static void main(String[] args) { //初始化可重入锁 final Lock lock = new ReentrantL…
newFixedThreadPool 创建一个固定大小的线程池. shutdown():用于关闭启动线程,如果不调用该语句,jvm不会关闭. awaitTermination():用于等待子线程结束,再继续执行下面的代码.该例中我设置一直等着子线程结束. Java代码 收藏代码 public class Test { public static void main(String[] args) throws IOException, InterruptedException { Executor…
这一部分来说说线程池如何进行状态控制,即线程池的开启和关闭. 先来说说线程池的开启,这部分来看ThreadPoolExecutor构造方法: public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecut…
0. Collections.synchronizedXxx() Java 中常用的集合框架中的实现类:HashSet/TreeSet.ArrayList/LinkedList.HashMap/TreeMap 都不是线程安全的.即如果存在多个线程访问它们,并且有超过一个的线程试图修改它们,便存在线程安全的问题: Collection c = Collections.synchronizedCollection(new ArrayList()); List list = Collections.s…
并发框架分类 1. Executor相关类 Interfaces. Executor is a simple standardized interface for defining custom thread-like subsystems, including thread pools, asynchronous I/O, and lightweight task frameworks. Depending on which concrete Executor class is being u…
Introduction to Functional Interfaces – A concept recreated in Java 8 Any java developer around the world would have used at least one of the following interfaces: java.lang.Runnable,java.awt.event.ActionListener, java.util.Comparator,java.util.concu…
Condition接口 应用场景:一个线程因为某个condition不满足被挂起,直到该Condition被满足了. 类似与Object的wait/notify,因此Condition对象应该是被多线程共享的,需要使用锁保护其状态的一致性 示例代码: class BoundedBuffer { final Lock lock = new ReentrantLock(); final Condition notFull = lock.newCondition(); final Conditio…
在写前面两篇文章23和24的时候自己有很多细节搞得不是很明白,这篇文章把Fork和Work-Stealing相关的源代码重新梳理一下. 首先来看一些线程池定义的成员变量: 关于scanGuard: volatile int scanGuard; private static final int SG_UNIT = 1 << 16; private static final int SMASK = 0xffff; scanGuard低位16位数值(0到15位)始终等于2的N次方减去1,代表的是大…