计数器CyclicBarrier/CountDownLatch,Semaphore信号量
+1计数器CyclicBarrier
package add;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/**CyclicBarrier +1计数器
* @author liu
*/
public class CyclicBarrierA {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
System.out.println("召唤神龙成功");
});
for (int i = 1; i <=7 ; i++) {
final int finalI = i;
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"收集了"+ finalI +"个龙珠");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
-1计数器CountDownLatch
package add;
import java.util.concurrent.CountDownLatch;
/**CountDownLatch -1计数器
* @author liu
*/
public class CountDownLatchA {
public static void main(String[] args) throws InterruptedException {
//总数是6,必须要执行的任务的时候再使用
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 1; i <=6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+" GO OUT");
//计数减一
countDownLatch.countDown();
},String.valueOf(i)).start();
}
//等待计数器归零,然后再向下执行
countDownLatch.await();
System.out.println("close door");
}
}
Semaphore信号量
package add;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SemaphoreA {
public static void main(String[] args) {
//线程数量:停车位!限流,限制3个进入
Semaphore semaphore = new Semaphore(3);
for (int i = 1; i <=6; i++) {
new Thread(()->{
try {//acquire 得到
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"抢到车位");
TimeUnit.SECONDS.sleep(1);
System.out.println(Thread.currentThread().getName()+"离开车位");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//release 释放
semaphore.release();
}
},String.valueOf(i)).start();
}
}
}
分类:
JUC编程简介
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现