1、减法计数器
public static void main(String []args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 1;i<=6;i++){
new Thread(()->{
System.out.println(Thread.currentThread().getName()+" go out");
countDownLatch.countDown();
}).start();
}
countDownLatch.await();
System.out.println("close door");
}
2、加法计数器
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
System.out.println("Run");//先运行参数,达到目标值后运行lambda表达式中的代码
});
for (int i = 1; i <= 7; i++) {
final int temp = i;
new Thread(() -> {
//lambda表达式中不能直接取i,需要通过定义final私有的中间变量
System.out.println(Thread.currentThread().getName() + temp);
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
3、线程限流
public static void main(String[] args) {
//线程数量:限流
Semaphore semaphore = new Semaphore(3);
for (int i = 1;i<=6;i++){
new Thread(()->{
try {
semaphore.acquire();//得到
System.out.println(Thread.currentThread().getName()+"已入库");
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName()+"已出库");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();//释放
}
},String.valueOf(i)).start();
}
}
最后
以上就是执着小熊猫最近收集整理的关于JUC计数器(加法和减法)的全部内容,更多相关JUC计数器(加法和减法)内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复