JUC :java.util.concurrent(Java并发包)
JUC包下的所有类都是线程安全的,JUC下有:
1.ReentrantLock(可重入锁)
a.lock()一定要放在try之前
b.在finally里面一定要释放锁
2.Semaphore(信号量)
可以实现限流功能(类似于排队等待停车位)
//创建信号量
Semaphore semaphore=new Semaphore(2);
//创建线程池
ThreadPoolExecutor executor=new ThreadPoolExecutor(10,10,0, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1000));
//执行任务1
executor.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"到达停车场门口");
try {
Thread.sleep(1000);
//尝试获取锁
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
//执行到此行代码表示已经获取到了停车位
System.out.println(Thread.currentThread().getName()+"进入了停车场");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"离开了停车场");
//释放锁
semaphore.release();
}
});
3.CountDownLatch(计数器)
等待所有的线程进入某个步骤之后,再统一执行某个流程。
这就好像田径比赛,当所有的选手都到达终点之后,再来宣布成绩。
面试题:CountDownLatch的实现原理?
CountDownLatch执行的原理就是内部有一个计数器,当执行了countdown方法后计数器-1,直到减为0那么这个计数器就使用完毕了,就可以执行await方法之后的代码了。
CountDownLatch缺点:计数器只能使用一次。
4.CyclicBarrier(循环屏障)
public static void main(String[] args) {
CyclicBarrier cyclicBarrier=new CyclicBarrier(2, new Runnable() {
@Override
public void run() {
System.out.println("-------------到达了屏障---------");
}
});
ThreadPoolExecutor executor=new ThreadPoolExecutor(10,10,0, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1000));
for(int i=0;i<6;i++){
final int finalI=i;
executor.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(finalI*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"执行任务");
try {
//会阻塞等待所有线程的数量满足屏障的数量,
//只有满足了循环屏障的数量才能继续往下执行
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"执行结束");
}
});
}
}
CyclicBarrier执行原理:内部有一个计数器,每次线程执行到await方法的时候,计数器+1,直到计数器个数等于创建时声明的个数的时候,就会突破屏障,执行之后的代码;在突破屏障之后计数器清零,可以进行下一轮的执行。
面试题:CountDownLatch和CyclicBarrier区别?
答:CountDownLatch它的计数器只能使用一次,CyclicBarrier可以反复使用