目录
1.ReentrantLock:可重入锁
2.Semaphore:信号量
3.CountDownLatch:计数器
4.CyclicBarrier:循环屏障
之前文章有详解:加锁&释放锁~
设置传参表示颁发了几个令牌。可以做程序的限流操作。控制并发量。
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;/*** 信号量:实现限流*/
public class SemaphoreDemo1 {public static void main(String[] args) {//创建线程池ExecutorService service = Executors.newFixedThreadPool(5);//创建信号量,默认情况下也是非公平锁【若要设置公平锁,只需要设置第二个参数true】Semaphore semaphore = new Semaphore(2); //表示同时可以一起执行的线程只有2个//统一任务的定义Runnable runnable = new Runnable() {@Overridepublic void run() {Thread currentThread = Thread.currentThread(); //得到执行此任务的线程System.out.println("进入线程:" + currentThread.getName());try {//获取令牌semaphore.acquire(); //如果没有可用令牌的话,那么线程会阻塞在当前位置System.out.println(currentThread.getName() + ":得到了令牌 | Time:" + LocalDateTime.now());TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {e.printStackTrace();} finally{System.out.println(currentThread.getName() + ":释放了令牌 | Time:" + LocalDateTime.now());//释放令牌semaphore.release();}}};//定义新线程执行任务service.submit(runnable);//定义新线程执行任务service.submit(runnable);//定义新线程执行任务service.submit(runnable);//定义新线程执行任务service.submit(runnable);//定义新线程执行任务service.submit(runnable);}
}
公平锁:
import java.time.LocalDateTime;
import java.util.concurrent.Semaphore;/*** 信号量:实现限流*/
public class SemaphoreDemo1 {public static void main(String[] args) {//创建信号量,默认情况下也是非公平锁【若要设置公平锁,只需要设置第二个参数true】Semaphore semaphore = new Semaphore(10, true);for (int i = 0; i < 1000; i++) {try {Thread.sleep(i * 100);} catch (InterruptedException e) {e.printStackTrace();}new Thread(new Runnable() {@Overridepublic void run() {Thread currentThread = Thread.currentThread();//得到执行此任务的线程try {//获取令牌semaphore.acquire();//如果没有可用令牌的话,那么线程会阻塞在当前位置System.out.println(currentThread.getName() + ":得到了令牌 | Time:" + LocalDateTime.now());Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();} finally {//释放令牌semaphore.release();}}}).start();}}
}
非公平锁:
Semaphore semaphore = new Semaphore(10, false);
CountDownLatch方法:判断线程池的任务是否已经全部执行完,线程安全的。其中有2个方法:
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;/*** 计数器使用*/
public class CountDownLatchDemo1 {public static void main(String[] args) throws InterruptedException {//创建计数器CountDownLatch countDownLatch = new CountDownLatch(5); //参加任务的数量//创建线程池ExecutorService service = Executors.newFixedThreadPool(5);//创建新线程执行任务for (int i = 1; i < 6; i++) {service.submit(() -> {Thread currThread = Thread.currentThread();System.out.println(currThread.getName() + "开始起跑");//跑步所用时间 1 + (0 - 4) 最长跑5s,最短跑1sint runTime = (1 + new Random().nextInt(5));try {TimeUnit.SECONDS.sleep(runTime);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(currThread.getName() + ":到达终点。用时:" + runTime);countDownLatch.countDown(); //计数器-1});}countDownLatch.await();//阻塞等待,直到线程执行完System.out.println("比赛结果宣布");}
}
CyclicBarrier可以看做是一个可以重复利用的CountDownLatch(一次性的),可实现线程分组的阻塞。其中的1个重要方法:
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;/*** 循环屏障*/
public class CyclicBarrierDemo1 {public static void main(String[] args) {//循环屏障CyclicBarrier cyclicBarrier = new CyclicBarrier(5, new Runnable() {@Overridepublic void run() {System.out.println("计数器为0了");}});//创建线程池ExecutorService service = Executors.newFixedThreadPool(10);for (int i = 0; i < 10; i++) {int finalI = i;service.submit(() -> {Thread currThread = Thread.currentThread();System.out.println("执行线程:" + currThread.getName());try {Thread.sleep(5 * finalI);cyclicBarrier.await(); //执行阻塞等待(计数器-1,阻塞等待,直到循环屏障计数器为0的时候,再执行后面的代码)} catch (InterruptedException e) {e.printStackTrace();} catch (BrokenBarrierException e) {e.printStackTrace();}System.out.println("线程执行完成:" + currThread.getName());});}}
}