CountDownLatch
是JUC下提供的一个计数器,其通过计数递减的方式控制线程的执行顺序。当CountDownLatch的计数器减到0的时候,CountDownLatch.await()阻塞的线程将会被唤醒。
package com.leolee.multithreadProgramming.juc.countDownLatch;
import java.util.concurrent.CountDownLatch;
/**
* @ClassName CountDownLatchTest
* @Description: TODO
* @Author LeoLee
* @Date 2021/3/2
* @Version V1.0
**/
public class CountDownLatchTest {
public static void main(String[] args) throws InterruptedException {
CountDownLatchTest.test1();
}
public static void test1() throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 0; i < 6; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "离开教室");
countDownLatch.countDown();
}, String.valueOf(i)).start();
}
countDownLatch.await();
System.out.println("所有人离开教室," + Thread.currentThread().getName() + "开始锁门");
}
}
CyclicBarrier
与CountDownLatch相反,CyclicBarrier是做累加的计数器,待计数器累加到预期值之后,指定线程即可开始运行。
package com.leolee.multithreadProgramming.juc.cyclicBarrier;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/**
* @ClassName CyclicBarrierTest
* @Description: TODO
* @Author LeoLee
* @Date 2021/3/2
* @Version V1.0
**/
public class CyclicBarrierTest {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7, new Runnable() {
@Override
public void run() {
System.out.println("累加到7,最终线程开始执行");
}
});
for (int i = 0; i < 7; i++) {
int tempInt = i;
new Thread(() -> {
System.out.println("累加到" + tempInt);
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}, String.valueOf(i)).start();
}
}
}
Semaphore
Semaphore是JUC提供的对多线程访问资源进行并发控制的工具,其可以达到多线程竞争有限资源场景下的访问限流效果。
package com.leolee.multithreadProgramming.juc.semaphore;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.Semaphore;
/**
* @ClassName Test
* @Description: Semaphore信号量
* 主要作用:
* 1.用于多个共享资源的互斥使用
* 2.控制并发线程数
* @Author LeoLee
* @Date 2020/12/4
* @Version V1.0
**/
@Slf4j
public class Test {
/*
* 功能描述: <br>
* 〈Semaphore 的一般使用〉
* 使用抢车位的场景,车多车位少
* @Param: []
* @Return: void
* @Author: LeoLee
* @Date: 2020/12/4 15:56
*/
public void semaphoreTest() {
Semaphore semaphore = new Semaphore(3);
//有6辆车来抢车位
for (int i = 0; i < 6; i++) {
new Thread(() -> {
try {
//Semaphore的3会-1,即一个资源被占用了(acquire方法是占用一个资源,如果没有占用到资源将一直等待下去)
semaphore.acquire();
log.info("Thread{}占用了一个停车位", Thread.currentThread().getName());
//三秒钟之后车就开走了,即释放资源
Thread.sleep(3*1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//释放资源,+1
semaphore.release();
}
}, String.valueOf(i)).start();
}
}
public static void main(String[] args) {
Test test = new Test();
test.semaphoreTest();
}
}