一、volatile作用
- 保证线程可见性:堆内存是所有线程共享里面的内存,除此之外,每个线程都有自己的专属区域,如果共享内存里有一个值,当我们线程要去访问这个值,会将这个值copy一份当自己的工作空间,对这个值进行改变。改完之后马上写回去,但什么时候去检查有没有新的值无法控制。加了volatile就可以保证线程里面发生的改变在线程之间是可见的。底层是采用了MESI缓存一致性协议。
- 禁止指令重排序:cpu为了提升效率,执行一条指令会并发的执行,每次写都会被线程度读到,加了volatile,cpu就会按着顺序一步一步的执行(CPU层面是加了读屏障和写屏障)。
二、简单理解锁优化
- 最简单的锁力度变细或者锁力度变粗,锁力度变细的意思就是加锁代码(业务代码)少一点,锁力度变粗反之,正常情况syn征用不是很剧烈的前提粒度小一些,不排除在同一块方法中加了多个syn,这种可以选择变粗,减少锁的征用。
三、cas(compareAndSwap/compareAndSet)
- 无锁优化(自旋锁)
- Atomic开头的类(原子的),内部实现就是带锁的但并不是syn重量级锁,而是用cas来操作的,cas实现方法有三个参数cas(value,expected,newValue),附上伪代码
if v== expected v = newValue otherWise try again or fail
- ABA问题:Atomic保证了原子性,但会出现ABA问题,即我拿到了1,想变成2,1用cas操作,期望值是1准备变成2,过程中有一个线程把1变成2又变回1,中间值改过但是结果没变,不会影响cas,这就是ABA问题,解决ABA问题可以增加一个版本号,AtomicStampedReference这个类是可以解决ABA问题的。
- Atomic开头的类(原子的),内部实现就是带锁的但并不是syn重量级锁,而是用cas来操作的,cas实现方法有三个参数cas(value,expected,newValue),附上伪代码
四、ReentrantLock
- 概念介绍:可重入锁,syn也是可重入的,可重入的概念是我锁了一下还可以对同样的这把锁在锁一下
/**
* reentrantlock用于替代synchronized
* 本例中由于m1锁定this,只有m1执行完毕的时候,m2才能执行
*/
import java.util.concurrent.TimeUnit;
public class ReentrantLock1 {
synchronized void m1() {
for(int i=0; i<10; i++) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i);
if(i == 2) m2();
}
}
synchronized void m2() {
System.out.println("m2 ...");
}
public static void main(String[] args) {
ReentrantLock1 rl = new ReentrantLock1 ();
new Thread(rl::m1).start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
//new Thread(rl::m2).start();
}
}
- ReentrantLock可以替代syn,原来syn的地方替换成lock.lock();,结束后lock.unlock();解锁,这是因为syn是自动解锁,ReentrantLock必须放在try-finally中代码如下:
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLock2 {
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) {
ReentrantLock2 rl = new ReentrantLock2 ();
new Thread(rl::m1).start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(rl::m2).start();
}
}
- ReentrantLock方法介绍与syn对
- tryLock(),进行尝试锁定,不论锁定与否都将继续执行下面代码。
- lockInterruptibly();对interrupt()方法做出了响应,可以被打断的锁,t1线程使用lockInterruptibly(),t2线程中可以interrupt()打断:源码附上
/** * Acquires in exclusive mode, aborting if interrupted. * Implemented by first checking interrupt status, then invoking * at least once {@link #tryAcquire}, returning on * success. Otherwise the thread is queued, possibly repeatedly * blocking and unblocking, invoking {@link #tryAcquire} * until success or the thread is interrupted. This method can be * used to implement method {@link Lock#lockInterruptibly}. * * @param arg the acquire argument. This value is conveyed to * {@link #tryAcquire} but is otherwise uninterpreted and * can represent anything you like. * @throws InterruptedException if the current thread is interrupted */ public final void acquireInterruptibly(int arg) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); if (!tryAcquire(arg)) doAcquireInterruptibly(arg); }
- 还可以指定公平非公平,默认是非公平的,效率大概是公平的5-10倍(没试过,看别人说的),参数为true就是公平的,即线程会先检查队列中有没有原来等着的,如果有就先进入队列等待别人先运行。
五、CountDownLatch
源码中的一段话这么说的:A synchronization aid that allows one or more threads to wait until.a set of operations being performed in other threads completes.一种同步辅助工具,允许一个或多个线程等待。在其他线程中执行的一组操作完成。
- 他的功能和join类似,但是可以控制的更精确,new100个线程,100个数量的CountDownLatch,每一次线程结束,latch.countDown();,然后线程start, 然后latch.await();执行countDown会减一,执行到await时候会等待,减到0之后就会打开这个“栓”,执行后面代码
import java.util.concurrent.CountDownLatch;
public class TestCountDownLatch {
public static void main(String[] args) {
usingJoin();
usingCountDownLatch();
}
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<10000; j++) result += j;
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");
}
private static void usingJoin() {
Thread[] threads = new Thread[100];
for(int i=0; i<threads.length; i++) {
threads[i] = new Thread(()->{
int result = 0;
for(int j=0; j<10000; j++) result += j;
});
}
for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
for (int i = 0; i < threads.length; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("end join");
}
}
六、CyclicBarrier
源码注释: A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads
are released.
- 用法:可以传两个参数,第二个可以不传,第一个参数表示满了之后调用第二个参数的动作,到了第一个参数的数量,await才会放开执行,一般可以运用在访问数据库,访问网络,访问文件,可以顺序执行,效率低,可以用CyclicBarrier并发执行,全部完毕了在就进行接下来操作。
import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; public class TestCyclicBarrier { public static void main(String[] args) { //CyclicBarrier barrier = new CyclicBarrier(20); CyclicBarrier barrier = new CyclicBarrier(20, () -> System.out.println("满人")); /*CyclicBarrier barrier = new CyclicBarrier(20, new Runnable() { @Override public void run() { 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(); } } }
七、Phaser
- 类似CountDownLatch和CyclicBarrier结合,是一个分阶段的“栅栏”。
- 按照不同的阶段来对线程进行执行,本身维护着一个阶段这样的一个成员变量,当前我执行到那个阶段,第0个或者第1个等等。每个阶段不同的时候这个线程都可以往前走,有的线程走到了某个阶段就停了,有的会一直到结束,程序中分好几个阶段,且有的比得多个共同参与时可以用到。下面是模拟代码:
- 代码中phaser.bulkRegister(7);方法给定一个数量
import java.util.Random;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;
public class TestPhaser {
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();
}
}
}
八、ReadWriteLock
- 读写锁(共享锁和排它锁),读锁就是共享,写锁就是排他
- 读锁之间是不加锁的(读与读),写锁之间是加锁的(读与写,写与写)
- 下面代码中测试了ReentrantLock和ReadWriteLock,如果使用ReentrantLock,这把锁加上其他任何线程都拿不到,每个线程执行需1s,大概要20s。而 ReadWriteLock分出两把锁readLock和writeLock,读线程是可以一起读的,18个线程大概1s就可以完成,提高了性能。
import java.util.Random; import java.util.concurrent.atomic.LongAdder; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class TestReadWriteLock { 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(); } }
九、Semaphore
- 信号灯,可同时控制几个线程执行,限流(最多有几个线程同时运行)。acquire获取锁,release释放锁。Semaphore也可设置为公平。
import java.util.concurrent.Semaphore; public class TestSemaphore { public static void main(String[] args) { //Semaphore s = new Semaphore(2); Semaphore s = new Semaphore(2, true); //允许一个线程同时执行 //Semaphore s = new Semaphore(1); new Thread(()->{ try { s.acquire(); System.out.println("T1 running..."); Thread.sleep(200); System.out.println("T1 running..."); } catch (InterruptedException e) { e.printStackTrace(); } finally { s.release(); } }).start(); new Thread(()->{ try { s.acquire(); System.out.println("T2 running..."); Thread.sleep(200); System.out.println("T2 running..."); s.release(); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); } }
十、Exchanger
-
交换器,两个线程之间交换数据,具体场景例如游戏中的交换装备。
- 第一个线程执行到 exchanger.exchange(s);,阻塞,第二个线程执行到 exchanger.exchange(s);也仍了一个值进去,交换,两个线程继续执行。
import java.util.concurrent.Exchanger; public class TestExchanger { static Exchanger<String> exchanger = new Exchanger<>(); public static void main(String[] args) { new Thread(()->{ String s = "T1"; try { s = exchanger.exchange(s); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " " + s); }, "t1").start(); new Thread(()->{ String s = "T2"; try { s = exchanger.exchange(s); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " " + s); }, "t2").start(); } }