J.U.C之AQS
AbstractQueuedSynhronizer
底层双向链表队列的一种实现
使用Node实现FIFO队列,可以用于构建锁或者其他同步装置的基础框架
利用了一个int类型表示状态
使用方法继承,设计是使用模版方法,子类通过继承并通过实现他的方法来管理其状态{acquire 和 release}的方法操纵状态
可以同时实现拍他锁和共享锁模式(独占、共享)
AQS同步组件
CountDownLatch,闭锁,通过一个计数来保证线程是否需要一直阻塞
private static final int threadCount=200;
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService =
Executors.newCachedThreadPool();
final CountDownLatch downLatch=new CountDownLatch(threadCount);
for (int i = 0; i < threadCount; i++) {
final int count=i;
executorService.execute(()->{
try
{
test(count);
}catch(Exception ex){
log.info("{}",ex.getMessage());
}finally{
downLatch.countDown();
}
});
}
downLatch.await();
log.info("{}","fistish");
executorService.shutdown();
}
private static void test(int i){
try {
Thread.sleep(100);
log.info("{}",i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
注:主要方法countDown、await,await函数需要等待countDown计数为0,才继续执行,调用线程池,用完了需要关闭showDown是需要等到当前给定线程继续执行完才能继续执行,downLatch.await(10, TimeUnit.MILLISECONDS);添加等待时间
Semaphore:控制同一时间并发线程数目,信号量,并发访问控制
final Semaphore semaphore=new Semaphore(3);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < threadCuont; i++) {
final int count=i;
executorService.execute(()->{
try {
if(semaphore.tryAcquire(1000, TimeUnit.MILLISECONDS)){
// semaphore.acquire(3);
test(count);
semaphore.release(3);
}
} catch (InterruptedException e) {
e.printStackTrace