JUC 常见的锁
}
long end = System.currentTimeMillis();
System.out.println("AtomicLong: " + count1.get() + " time: " + (end - start));
//long
Object o = new Object();
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 100000; j++) {
synchronized (o) {
count2++;
}
}
});
}
start = System.currentTimeMillis();
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join();
}
end = System.currentTimeMillis();
System.out.println("Long: " + count2 + " time: " + (end - start));
//LongAdder
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 100000; j++) {
count3.increment();
}
});
}
start = System.currentTimeMillis();
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join();
}
end = System.currentTimeMillis();
System.out.println("LongAdder: " + count3.longValue() + " t 《一线大厂 Java 面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 ime: " + (end - start));
}
}
复制代码
LongAdder 内部用的是分段锁(内部也是 CAS 实现)。它会把值放到一个数组里,比如数组大小为 4,则每一个数组里锁 250 个线程,每一个数组都做运算,最后再把所有的数组结果求和。所以 LongAdder 在超高并发时,优势特别明显。
二、ReentrantLock
===============
1、reentrantlock 可以代替 synchronized,使用 reentrantlock 可以完成和 synchronized 同样的功能,但是必须得手动释放锁。使用 synchronized 锁定如果遇到异常,jvm 会自动释放锁,但是 ReentrantLock 必须手动释放锁,因此经常在 finally 中释放锁。
2、使用 reentrantlock 可以进行尝试锁定(tryLock),这样无法锁定或者在指定时间内无法锁定,线程可以决定是否继续等待。
3、reentrantlock 可以指定为公平锁。ReentrantLock lock=new ReentrantLock(true);表示 new 一个公平锁。默认是非公平锁。
1、公平锁与非公平锁
公平锁:如果一个新来的线程,首先去判断锁的等待队列有无正在等待的线程,有则进入等待队列,等前面的先运行,无则直接去抢锁,这样的锁是公平锁。先来后到。
非公平锁:如果一个新来的线程,直接就去抢锁,而不去判断等待队列是否有线程在等待,这就是非公平锁。synchronized 都是非公平锁。
新来的线程检不检查队列是公平锁与非公平锁的关键。
2、reentrantlock VS synchronized
1、reentrantlock 可以代替 synchronized
2、reentrantlock 必须手动关闭锁,synchronized 执行结束或异常时 JVM 会自动释放锁
3、reentrantlock 是通过 CAS 实现的,synchronized 本质是锁升级
4、reentrantlock 可以通过 tryLock 来进行尝试锁定
5、reentrantlock 可以在公平锁与非公平锁之间切换,synchronized 都是非公平锁
三、CountDownLatch(倒数 门闩)
=======================
/**
@author Java 和算法学习:周一
*/
public class TestCountDownLatch {
public static void usingCountDownLatch() {
Thread[] threads = new Thread[10];
CountDownLatch countDownLatch = new CountDownLatch(threads.length);
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(() -> {
int count = 0;
for (int j = 0; j < 10000; j++) {
count++;
}
System.out.println(count);
countDownLatch.countDown();
});
}
for (Thread thread : threads) {
thread.start();
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("CountDownLatch end...");
}
public static void main(String[] args) {
usingCountDownLatch();
}
}
复制代码
countDownLatch 初始大小定义为 10,每增加一个线程门闩值减 1(countDownLatch.countDown()), 一直等待着(countDownLatch.await()),直到门闩值为 0 才执行。
四、CyclicBarrier (循环 栅栏)
=======================
/**
@author Java 和算法学习:周一
*/
public class TestCyclicBarrier {
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(20, ()->{
System.out.println("满人,发车");
});
for (int i = 0; i < 100; i++) {
new Thread(()->{
try {
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
复制代码
CyclicBarrier 大小定义为 20,达到 20 个线程时才执行一次,否则一直等待着(barrier.await())。即以上程序会输出 5 次 满人,发车。
五、Phaser
========
/**
@author Java 和算法学习:周一
*/
public class TestPhaser {
private static MarriagePhaser marriagePhaser = new MarriagePhaser();
public static void sleep() {
try {
TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class MarriagePhaser extends Phaser {
@Override
protected boolean onAdvance(int phase, int registeredParties) {
switch (phase) {
case 0:
System.out.println("所有人到齐 " + registeredParties);
System.out.println();
return false;
case 1:
System.out.println("所有人吃完 " + registeredParties);
System.out.println();
return false;
case 2:
System.out.println("所有人离开 " + registeredParties);
System.out.println();
return false;
case 3:
System.out.println("新郎新娘抱抱 " + registeredParties);
return true;
default:
return true;
}
}
}
static class Person implements Runnable {
String name;
public Person(String name) {
this.name = name;
}
private void arrive() {
sleep();
System.out.println(name + " 到达现场");
marriagePhaser.arriveAndAwaitAdvance();
}
private void eat() {
sleep();
System.out.println(name + " 吃");
marriagePhaser.arriveAndAwaitAdvance();
}
private void leave() {
sleep();
System.out.println(name + " 离开");
marriagePhaser.arriveAndAwaitAdvance();
}
private void hug() {
if ("新郎".equals(name) || "新娘".equals(name)) {
sleep();
System.out.println(name + " 拥抱");
marriagePhaser.arriveAndAwaitAdvance();
} else {
marriagePhaser.arriveAndDeregister();
}
}
@Override
public void run() {
arrive();
eat();
leave();
hug();
}
}
public static void main(String[] args) {
marriagePhaser.bulkRegister(7);
for (int i = 0; i < 5; i++) {
new Thread(new Person("person" + i)).start();
}
new Thread(new Person("新郎")).start();
new Thread(new Person("新娘")).start();
}
}
复制代码
类似于栅栏组,分阶段的栅栏 。所有的线程都到了某个栅栏的时候,才会执行下一步的操作。
六、ReadWriteLock
===============
Read 的时候是共享锁
Write 的时候是排它锁(互斥锁)
最开始如果是读线程拿到了锁,当第二个来的线程是读线程时,可以一起读;当第二个来的是写线程时则阻塞,不允许你写,等我读完再写。
最开始如果是写线程拿到了锁,不管第二个线程是读还是写,均阻塞,必须等我改完了其他线程才能读、其他线程才能写。
/**
@author Java 和算法学习:周一
*/
public class TestReadWriteLock {
private static int value;
private static ReentrantLock lock = new ReentrantLock();
private static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private static Lock readLock = readWriteLock.readLock();
private static Lock writeLock = readWriteLock.writeLock();
public static void read(Lock lock) {
try {
lock.lock();
Thread.sleep(1000);
System.out.println("read...");
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void write(Lock lock, int v) {
try {
lock.lock();
value = v;
Thread.sleep(1000);
System.out.println("write..." + value);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
//读线程 8 个
Thread[] tRead = new Thread[8];
for (int i = 0; i < 8; i++) {
tRead[i] = new Thread(() -> {
read(readLock);
});
}
long start = System.currentTimeMillis();
for (Thread t : tRead) {
t.start();
}
for (Thread t : tRead) {
t.join();
}
评论