本篇主要介绍java中的各种锁,分析各种锁的特点和可能的运用场景======
Sync 、LongAdder 、AtomicLong 的效率分析比较
public class TestXiaoLv {
public static final long cycleCount = 10000;
public static final long threadCounts = 100000;
public static volatile Long count01 = 0L;
public static volatile LongAdder count02 = new LongAdder();
public static volatile AtomicLong count03 = new AtomicLong(0L);
public synchronized static void m1(){
for(int i = 0; i < cycleCount; i++){
count01++;
}
}
public static void m2(){
for(int i = 0; i < cycleCount; i++) {
count02.increment();
}
}
public static void m3(){
for(int i = 0; i < cycleCount; i++) {
count03.incrementAndGet();
}
}
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
for (int i = 0; i < threadCounts; i++) {
new Thread(() -> m1()).start();
}
while (count01<cycleCount*threadCounts) {
//System.err.println(count01);
}
System.err.println(count01);
System.out.println((System.currentTimeMillis() - start));
start = System.currentTimeMillis();
for (int i = 0; i < threadCounts; i++) {
new Thread(()->m2()).start();
}
while (count02.longValue()<cycleCount*threadCounts) {
//System.err.println(count02.longValue());
}
System.err.println(count02.longValue());
System.out.println((System.currentTimeMillis() - start));
start = System.currentTimeMillis();
for (int i = 0; i < threadCounts; i++) {
new Thread(()->m3()).start();
}
while (count03.longValue() < cycleCount*threadCounts) {
//System.err.println(count03.longValue());
}
System.err.println(count03.longValue());
System.out.println((System.currentTimeMillis() - start));
}
}
当线程数只有10的时候,sync的效率最低,longadder其次,atomiclong最高
当线程数提高到10000时,atomic效率最低,sync其次,longadder最高
sync锁和atomicLong的取舍
- 我们可以发现,longadder的表现非常好,sync的效率随着线程数的提高反超了atomiclong,这是因为sync锁具有一个锁升级概念,当出现大量锁争用情况的时候会升级为OS锁,反而效率高于自旋锁;atomiclong底层时cas,相当于是自旋,在线程数量高的时候,争用情况严重的时候,反而不如os锁
longadder原理简介
- longadder是分段锁,所有的thread分成数个部分,每一个部分有自己独立的变量来进行递增,最后再将每一个部分递增了之后的结果进行一个sum,最后返回结果
ReentrantLock介绍
ReentrantLock使用
public class ReentrantLock_01 {
Lock lock = new ReentrantLock();
void m1() {
try {
lock.lock(); //synchronized(this)
for (int i = 0; i < 10; i++) {
TimeUnit.SECONDS.sleep(1);
System.out.println(i);
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
void m2() {
try {
lock.lock();
System.out.println("m2 ...");
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
ReentrantLock_01 rl = new ReentrantLock_01();
new Thread(rl::m1).start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(rl::m2).start();
}
}
- 我们可以发现,线程一在上锁之后线程二无法执行,直到线程一解锁,线程二才开始执行
- 我们要注意,ReentrantLock的lock和unlock要写在 try finally中,这样可以防止在lock期间出现问题,锁一直没有解锁
- 我们还可以使用 trylock命令,来尝试上锁,不论是否得到锁都会执行后面的代码
ReentrantLock的锁打断
public class T04_ReentrantLock4 {
public static void main(String[] args) {
Lock lock = new ReentrantLock();
Thread t1 = new Thread(()->{
try {
lock.lock();
System.out.println("t1 start");
TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
System.out.println("t1 end");
} catch (InterruptedException e) {
System.out.println("interrupted!");
} finally {
lock.unlock();
}
});
t1.start();
Thread t2 = new Thread(()->{
try {
//lock.lock();
lock.lockInterruptibly(); //可以对interrupt()方法做出响应
System.out.println("t2 start");
TimeUnit.SECONDS.sleep(5);
System.out.println("t2 end");
} catch (InterruptedException e) {
System.out.println("interrupted!");
} finally {
lock.unlock();
}
});
t2.start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.interrupt(); //打断线程2的等待
}
}
- 当我们启动了一个线程的时候,这个线程已经被lock上了,但是我们还可以通过另外一个线程来打断这个lock
ReentrantLock的公平锁
ReentrantLock lock = new ReentrantLock(true);
- 当我们在创建 ReentrantLock 对象的时候,如果我们传入 boolean true值,那么这个 lock 就会变为公平锁
- 公平锁的意思是,当线程在ready队列的时候会挨着按照先来后到的顺序使用锁;如果不是公平锁的话,那么就是所有锁都进行锁争用,没有先来后到之分
ReentrantLock和Synchronized锁的比较
- ReentrantLock 和 Sync 都是可重入锁——当一个线程对一个对象加锁的时候如果发现这个锁资源已经被这个线程得到的话会直接执行,不会被阻塞住
- ReentrantLock可以转换为公平锁,sync只有非公平锁
- ReentrantLock锁可以被打断,sync锁无法被打断
CountDownLatch介绍
CountDownLatch使用
- CountDownLatch非常像一个“门闩”
private static void usingCountDownLatch() {
Thread[] threads = new Thread[100];
CountDownLatch latch = new CountDownLatch(threads.length);
for(int i=0; i<threads.length; i++) {
threads[i] = new Thread(()->{
int result = 0;
for(int j=0; j<10; j++) {
result += j;
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(result);
}
latch.countDown();
});
}
for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("end latch");
}
public static void main(String[] args) {
//usingJoin();
usingCountDownLatch();
}
}
- 我们有100个线程,每一个线程在被创建一段时间后就会countdown一下,我们一共有100道门闩,这个门闩被拴在主线程方法结束的前面,如果没有门闩的话,这个demo会在被启动后几乎立刻就结束,但是有了门闩就会让主线程在结束前被阻塞住,直到所有的门闩被打开
CyclicBarrier介绍
static CyclicBarrier barrier = new CyclicBarrier(5, ()-> System.out.println("达到二十人,发车"));
public static void main(String[] args) {
for(int i = 0; i < 20; i++){
new Thread(()->{
try {
System.err.println("thread start");
Thread.sleep(2);
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
System.out.println("main stop");
}
- CyclicBarrier是一个“栅栏”,当有一定数量的线程被栅栏阻挡的时候就会把栅栏放倒,让这些线程通过,这些线程通过之后,这个栅栏又会立起来,所以这是一个循环栅栏
CyclicBarrier和CountDownLatch的简单区别
- CyclicBarrier会将所有到来的线程给阻挡
- CountDownLatch是在一个线程的一个区域上门闩
- CyclicBarrier的线程+1是一个线程只能增加一次,CountDownLatch的CountDown可以在一个线程中多次CountDown
Phaser的简单介绍
static Random r = new Random();
static MarriagePhaser phaser = new MarriagePhaser();
static void milliSleep(int milli) {
try {
TimeUnit.MILLISECONDS.sleep(milli);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
phaser.bulkRegister(7);
for(int i=0; i<5; i++) {
new Thread(new Person("p" + i)).start();
}
new Thread(new Person("新郎")).start();
new Thread(new Person("新娘")).start();
}
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;
}
public void arrive() {
milliSleep(r.nextInt(1000));
System.out.printf("%s 到达现场!\n", name);
phaser.arriveAndAwaitAdvance();
}
public void eat() {
milliSleep(r.nextInt(1000));
System.out.printf("%s 吃完!\n", name);
phaser.arriveAndAwaitAdvance();
}
public void leave() {
milliSleep(r.nextInt(1000));
System.out.printf("%s 离开!\n", name);
phaser.arriveAndAwaitAdvance();
}
private void hug() {
if(name.equals("新郎") || name.equals("新娘")) {
milliSleep(r.nextInt(1000));
System.out.printf("%s 洞房!\n", name);
phaser.arriveAndAwaitAdvance();
} else {
phaser.arriveAndDeregister();
//phaser.register()
}
}
@Override
public void run() {
arrive();
eat();
leave();
hug();
}
}
- Phaser是阶段性栅栏,有点像障碍赛跑,当所有的线程达到第一个栅栏后,第一个栅栏会被放倒,一直持续,直到所有的栅栏都被放倒
ReadWriteLock读写锁(共享锁和排他锁)
static Lock lock = new ReentrantLock();
private static int value;
static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
static Lock readLock = readWriteLock.readLock();
static Lock writeLock = readWriteLock.writeLock();
public static void read(Lock lock) {
try {
lock.lock();
Thread.sleep(1000);
System.out.println("read over!");
//模拟读取操作
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void write(Lock lock, int v) {
try {
lock.lock();
Thread.sleep(1000);
value = v;
System.out.println("write over!");
//模拟写操作
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
//Runnable readR = ()-> read(lock);
Runnable readR = ()-> read(readLock);
//Runnable writeR = ()->write(lock, new Random().nextInt());
Runnable writeR = ()->write(writeLock, new Random().nextInt());
for(int i=0; i<18; i++) new Thread(readR).start();
for(int i=0; i<2; i++) new Thread(writeR).start();
}
- ReadWriteLock就是读写锁,读写锁分为读锁和写锁,读锁就是共享锁,写锁就是排他锁
- 当资源被读锁锁住时,其他的读锁可以一起读,但是读锁只能读无法改;当资源被写锁锁住时,其他的任何锁(包括读锁和写锁)都无法访问这个资源
- 读写锁可以极高地提高性能