目录
信号量Semphore
- 信号量Semaphore就是一个计数器,表示当前可用的资源的个数
- 两个核心操作 P申请资源操作 V是释放资源操作
Semapgore的PV操作都是原子性的
package SemaphoreTest; import java.util.concurrent.Semaphore; /** * 信号量的使用 */ public class Test { public static void main(String[] args) { //在构造方法中传入可用资源的个数 Semaphore semaphore=new Semaphore(5); Runnable runnable =new Runnable() { @Override public void run() { try { System.out.println(Thread.currentThread().getName()+"准备申请资源"); //P操作 申请一个资源 semaphore.acquire(); System.out.println(Thread.currentThread().getName()+"申请资源成功"); Thread.sleep(1000); System.out.println(Thread.currentThread().getName()+"释放一个资源"); //V操作 semaphore.release(); }catch (InterruptedException e){ } } }; for (int i = 0; i < 20; i++) { Thread t=new Thread(runnable,String.valueOf(i+1)); t.start(); } } }
CountDownLatch
- 类似大号的join方法,可以等待多个线程执行完毕,再继续执行
- 调用await方法,该线程会阻塞,直到所有等待线程全部执行完毕
package CountDownLatchTest; import Abstract.C; import java.util.Random; import java.util.concurrent.CountDownLatch; public class Test { public static void main(String[] args) throws InterruptedException { //等待线程需要等待的线程数,必须等待10个子线程执行完毕再恢复执行 CountDownLatch latch=new CountDownLatch(10); Runnable runnable=new Runnable() { @Override public void run() { try { Thread.sleep(new Random().nextInt(1000)); System.out.println(Thread.currentThread().getName()+"到达终点"); //计数器减1 latch.countDown(); }catch (InterruptedException e){ e.printStackTrace(); } } }; for (int i = 0; i < 10; i++) { Thread t=new Thread(runnable,"运动员"+i+1); t.start(); } //Main线程就是裁判线程,需要等待所有运动员跑完,才计数 //直到所有线程调用countdown方法将计数器减为0继续执行 latch.await(); System.out.println("比赛结束"); } }
juc下四个常用的工具类
- 信号量 Semapore
- 计数器CountDownLatch
- 循环栅栏CylicBarrier
- 交换器 Exchanger