JDK 1.5 开始,引入了并发工具包 java.util.concurrent.locks.Lock,让锁的功能更加丰富。
JUC中常见的锁有
- 可重入锁 Java.util.concurrent.lock.ReentrantLock
- 可重复读写锁 java.util.concurrent.lock.ReentrantReadWriteLock
1.Semaphore
是一个计数信号量,主要用于控制多线程对共同资源库访问的权限
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
class SemaphoreTest{
//最多只能5个可以获取
private static final Semaphore avialable = new Semaphore(5);
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(10);
Runnable r = new Runnable() {
@Override
public void run() {
try {
avialable.acquire();//次方法阻塞
Thread.sleep(10*1000);
System.out.println(Thread.currentThread().getName());
avialable.release();
}catch (InterruptedException e){
e.printStackTrace();
}
}
};
for (int i = 0; i < 10; i++) {
pool.execute(r);
}
pool.shutdown();
}
}
10秒后
pool-1-thread-1
pool-1-thread-3
pool-1-thread-4
pool-1-thread-2
pool-1-thread-5
再过十秒
pool-1-thread-6
pool-1-thread-7
pool-1-thread-10
pool-1-thread-9
pool-1-thread-8
2.ReentrantLock
可重入互斥锁.
synchronized
synchronized(object){
// working
}
ReentrantLock
ReentrantLock lock = new ReentrantLock();
-----------------------------------------
lock.lock();
try {
// working
}
finally {
lock.unlock()
}
class ReentrantLockTest{
static int n = 0;
public static void main(String[] args) {
Lock lock = new ReentrantLock();
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
lock.lock();
try {
add10000();
} finally {
lock.unlock();
}
}
}).start();
}
while (Thread.activeCount() > 2){
Thread.yield();
}
System.out.println(n);
}
public static void add10000(){
for (int i = 0; i < 10000; i++) {
n++;
}
}
}
3.CountDownLatch
类似跑步比赛 10个选手依次就位,哨声响了才同时出发;所有选手都通过重点,才能公布成绩
class CountDownLatchTest{
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(10);
Runnable r = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10000);
latch.countDown();
}catch (Exception e){
e.printStackTrace();
}
}
};
for (int i = 0; i < 10; i++) {
new Thread(r).start();
}
latch.await();//必须等到10个人全部回来
System.out.println("比赛结束");
}
}
5.4 原子类介绍
其实刚才我们以及看到了原子类的出现了,因为原子类内部用的是 CAS 实现,所以性能要比加锁实现 i++ 高很多。
原子类有以下几个
AtomicBoolean/AtomicInteger/AtomicIntegerArray/AtomicLong/AtomicReference/AtomicStampedReference
拿 AtomicInteger 举例,常见方法有
addAndGet(int delta); i += delta;
decrementAndGet(); --i;
getAndDecrement(); i–;
incrementAndGet(); ++i;
getAndIncrement(); i++;
-
JDK Atomic开头的类,是通过 CAS 原理解决并发情况下原子性问题。
-
CAS 包含 3 个参数,CAS(V, E, N)。V 表示需要更新的变量,E 表示变量当前期望值,N 表示更新为的 值。只有当变量 V 的值等于 E 时,变量 V 的值才会被更新为 N。如果变量 V 的值不等于 E ,说明变量 V 的值已经被更新过,当前线程什么也不做,返回更新失败。
-
当多个线程同时使用 CAS 更新一个变量时,只有一个线程可以更新成功,其他都失败。失败的线程不会被挂起,可以继续重试
CAS,也可以放弃操作。 -
CAS 操作的原子性是通过 CPU 单条指令完成而保障的。JDK 中是通过 Unsafe 类中的 API 完成的。
-
在并发量很高的情况,会有大量 CAS 更新失败,所以需要慎用。
https://www.javanav.com/interview/8499835a0ac54a369b7138de341d6ab0.html