synchronized
方法级
代码块级
异常自动释放
字符串? 必须同一个对象
wait() notify()
单例
1.
public static DubbleSingleton getInstance(){
if(instance== null){
synchronized (DubbleSingleton.class) {
if(instance == null){
instance= new DubbleSingleton();
}
}
}
return instance;
}
2.
private static class Singletion {
private static Singletion single = new Singletion();
}
public static Singletion getInstance(){
return Singletion.single;
}
CopyOnWriteArrayList
集合
ConcurrentHashMap
LinkedBlockingDeque
PriorityBlockingQueue 每次take()获取优先级最高,并非所有排序
ConcurrentLinkedQueue 高效非阻塞
ArrayBlockingQueue 非阻塞,个数限制
LinkedBlockingQueue 阻塞
SynchronousQueue 先take()
DelayQueue 定时器的实现、各种延迟关闭
Executors
/**
* 在使用有界队列时,若有新的任务需要执行,如果线程池实际线程数小于corePoolSize,则优先创建线程
* 若大于corePoolSize,则会将任务加入队列,
* 若队列已满,则在总线程数不大于maximumPoolSize的前提下,创建新的线程,
* 若线程数大于maximumPoolSize,则执行拒绝策略。或其他自定义方式。
*
* 无界队列,忽略maximumPoolSize如linkedBlockingQueue
拒绝策略用默认就行,或者自己实现
*/
ThreadPoolExecutor
ThreadPoolExecutor pool = new ThreadPoolExecutor(
1, //coreSize
2, //MaxSize
60, //60
TimeUnit.SECONDS,
new ArrayBlockingQueue(3) //指定一种队列 (有界队列)
//new LinkedBlockingQueue()
, new MyRejected()
//, new DiscardOldestPolicy()
);
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
CountDownLatch 主等待子任务完成
CyclicBarrier 多个子等待所有都完成,再一起往下执行
Callable
Future
Semaphore
Lock
ReentrantLock
lock.newCondition();
多condition
tryLock()
ReentrantReadWriteLock