Semaphore是什么:
Semaphore是计数信号量,他的作用是限制并发访问特定资源的线程数,底层是以来AQS的state属性来记录信号量,每个acquire方法阻塞,直到有一个许可证可以拿走获得;每个release方法释放一个信号量,这可能释放一个阻塞的acquire方法,这个许可证就是AQS中的state属性记录个数的。
构造方法:
//创建指定的信号量和非公平的对象
public Semaphore(int permits) {
sync = new NonfairSync(permits);
}
//创建指定的信号量和公平或非公平的对象
public Semaphore(int permits, boolean fair) {
sync = fair ? new FairSync(permits) : new NonfairSync(permits);
}
重要方法:
acquire():获取一个信号量,在获取不到一个信号量时会被阻塞,可以被其它线程中断;
acquire(int permits):和上个方法一样,区别在于需要获取指定的信号量;
tryAcquire():尝试获取信号量,直接返回成功true和失败false,不阻塞;
tryAcquire(long timeout, TimeUnit unit):在指定时间内获取到信号量或者超时,返回成功或失败;
acquireUninterruptibly():忽略中断获取信号量;
release():释放一个信号量;
release(int permits):释放指定信号量;
availablePermits():返回当前可用信号量;
hasQueuedThreads():返回等待队列中是否有等待的线程;
getQueueLength():返回等待线程估计的数量;
drainPermits():把当前可用的信号量清0,不在恢复;
使用场景:
资源访问、服务限流(Hystrix限流就是基于信号量)、数据库连接池(进行线程获取连接数的限制)
大致原理:
Semaphore semaphore = new Semaphore(2);
创建一个同步等待队列,不过队头和队尾都为null;
把信号量2赋值给AQS的state=2;
当有一个线程执行acquire方法时,信号量会减1,也就是state=state-1,执行release方法时,信号量加1,也就是state=state+1,不过这些赋值操作都是通过CAS完成的;当一个线程获取信号量时,可用的信号量不够时就会进入同步等待队列,但另一个线程释放信号量时会唤醒队列中的线程尝试获取信号量;
下面看一下重点方法的源码:
acquire()方法:
//获取一个信号量,获取不到就进行挂起等待
public void acquire() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
//获取一个信号量,获取不到就进行挂起等待
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
//判断里的方法是:尝试获取指定信号量,可用信号量减去获取信号量int remaining = available - acquires如果大于0,则进行CAS更新,都会把相减之后的数remaining返回
if (tryAcquireShared(arg) < 0)
//创建节点,加入阻塞队列队尾
//如果是对头节点则进行尝试获取信号量,如果成功,则唤醒后置节点进行尝试获取信号量;
//如果上个条件不满足,则进行先去除队列中无效节点,然后把当前节点的前驱节点的状态修改为SIGNAL
//最后当前线程进行挂起等待
doAcquireSharedInterruptibly(arg);
}
//创建节点,加入阻塞队列队尾
//如果是对头节点则进行尝试获取信号量,如果成功,则唤醒后置节点进行尝试获取信号量;
//如果上个条件不满足,则进行先去除队列中无效节点,然后把当前节点的前驱节点的状态修改为SIGNAL
//最后当前线程进行挂起等待
private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head) {
//唤醒后置节点进行尝试获取信号量
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return;
}
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
看看release方法:
public void release() {
sync.releaseShared(1);
}
/**
* Releases in shared mode. Implemented by unblocking one or more
* threads if {@link #tryReleaseShared} returns true.
*
* @param arg the release argument. This value is conveyed to
* {@link #tryReleaseShared} but is otherwise uninterpreted
* and can represent anything you like.
* @return the value returned from {@link #tryReleaseShared}
*/
public final boolean releaseShared(int arg) {
//释放共享锁:也就是 state=state+arg ,使用了自旋和CAS
if (tryReleaseShared(arg)) {
//唤醒同步等待队列中第一个线程
doReleaseShared();
return true;
}
return false;
}
//释放共享锁:也就是 state=state+arg ,使用了自旋和CAS
protected final boolean tryReleaseShared(int releases) {
for (;;) {
int current = getState();
int next = current + releases;
if (next < current) // overflow
throw new Error("Maximum permit count exceeded");
if (compareAndSetState(current, next))
return true;
}
}
/**
* Release action for shared mode -- signals successor and ensures
* propagation. (Note: For exclusive mode, release just amounts
* to calling unparkSuccessor of head if it needs signal.)
*/
//唤醒同步等待队列中第一个线程
private void doReleaseShared() {
/*
* Ensure that a release propagates, even if there are other
* in-progress acquires/releases. This proceeds in the usual
* way of trying to unparkSuccessor of head if it needs
* signal. But if it does not, status is set to PROPAGATE to
* ensure that upon release, propagation continues.
* Additionally, we must loop in case a new node is added
* while we are doing this. Also, unlike other uses of
* unparkSuccessor, we need to know if CAS to reset status
* fails, if so rechecking.
*/
for (;;) {
Node h = head;
if (h != null && h != tail) {
int ws = h.waitStatus;
if (ws == Node.SIGNAL) {
if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
continue; // loop to recheck cases
unparkSuccessor(h);
}
else if (ws == 0 &&
!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
continue; // loop on failed CAS
}
if (h == head) // loop if head changed
break;
}
}
CountDownLatch是什么?
其作用可以使一个或者多个线程等待其它线程执行完成再执行,其和CyclicBarrier 很相似,CyclicBarrier 是线程之前相互等待,当所有线程同时到达时,所有线程一起执行;其是通过一个计数器来实现的,使用的是AQS的state属性进行计数,当线程执行countDown()方法时,计数器就减1,当计数器等于0时,阻塞中的线程就会执行;
使用场景:
zookeeper分布式锁,Jmeter模仿高并发等;
常用方法:
CountDownLatch(int count):构造方法,创建一个值为count的计数器;
await() :如果计数器不为0,则阻塞当前线程,把当前线程加入到同步等待队列;
await(long timeout, TimeUnit unit):和上个方法的区别在于超时后,线程被唤醒并执行(阻塞方法中可以传入时间,到时间线程可以自动唤醒,这都是native方法);
countDown():对计数器进行减1操作,当计数器为0时,则唤醒所有阻塞的线程;
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(2);
for (int i = 0; i < 2; i++) {
new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "执行完毕");
countDownLatch.countDown();
}).start();
}
countDownLatch.await();
System.out.println(Thread.currentThread().getName() + "主线程执行完毕");
}
}
CyclicBarrier:
从名字看是‘循环屏障’,为什么叫这个名字呢,大概就是所有的线程都释放后,这个屏障可以重复使用;
这是一个辅助类,它允许一组线程相互等待,直到所有线程执行到一个公共的屏障点后,这一组线程接着屏障点一起执行;
构造方法:
CyclicBarrier(int parties)
CyclicBarrier(int parties, Runnable barrierAction)
parties参数是代表参与线程的个数;
Runnable barrierAction是值指定线程数都到达屏障点后要执行的任务;
使用场景:
可用于多线程计算数据,最后合并计算结果;
多个任务互不影响,但是最后需要统一归纳所有任务结果的场景;
重要方法:
await():线程执行此方法,代表已经到达屏障点,线程更被阻塞等待,直到指定数量的线程都到达屏障点,就唤醒所有阻塞的线程开始接着执行;
await(long timeout, TimeUnit unit):和上个方法作用一样,区别在于定义了阻塞时间;
代码示例:
//一个线程组的线程需要等待所有线程完成任务后再继续执行下一次任务
public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
CyclicBarrier cyclicBarrier = new CyclicBarrier(5, () -> {
System.out.println("所有线程已到达屏障点...");
});
for(int i=0;i<5;i++){
new Thread(()->{
try {
System.out.println(Thread.currentThread().getName()+"到达屏障点");
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"执行完毕");
}).start();
}
}
Exchanger:
用法:用于两个线程间的数据交换;
代码案例:
public static void main(String[] args) {
Exchanger<String> exchanger = new Exchanger();
new Thread(() -> {
String A = "线程A的数据";
try {
String exchange = exchanger.exchange(A);
System.out.println("线程A交换获取的数据" + exchange);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
String B = "线程B的数据";
try {
String exchange = exchanger.exchange(B);
System.out.println("线程B交换获取的数据" + exchange);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
打印结果: