【Java并发编程十】同步控制二

2023-11-22 08:20

本文主要是介绍【Java并发编程十】同步控制二,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Semaphore 信号量

 Semaphore可以减少负载,使限制同时运行的线程数量。Semaphore的执行过程是先获取一定数量的线程,执行完一个释放一个semaphore,再去执行一个新的线程。

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class myTest implements Runnable{// semaphore表示信号量final Semaphore semaphore = new Semaphore(5);public static void main(String[] args) {// 线程池ExecutorService executorService = Executors.newFixedThreadPool(20);final myTest test = new myTest();for(int i=0; i<20; i++) {executorService.submit(test);}}@Overridepublic void run() {try {long startTime = System.currentTimeMillis();// semaphore数量超过限制的数量,自身便会阻塞semaphore.acquire();Thread.sleep(2000);semaphore.release();long endTime = System.currentTimeMillis();System.out.println(Thread.currentThread().getId()+" cost " + (endTime-startTime) + " ms");} catch (InterruptedException e) {throw new RuntimeException(e);}}
}/**
由于设置semaphore最大数量为5,所以同一时刻最多有五个线程同时运行。
25 cost 2010 ms
27 cost 2010 ms
26 cost 2010 ms
24 cost 2010 ms
28 cost 2010 ms
33 cost 4010 ms
30 cost 4010 ms
29 cost 4019 ms
31 cost 4018 ms
32 cost 4018 ms
38 cost 6012 ms
35 cost 6012 ms
37 cost 6019 ms
43 cost 6019 ms
36 cost 6028 ms
*/

CountDownLatch 倒计时器

 CountDowmLatch是每次等到一定数量,end.await() 才会放行。

package myTest;import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;public class myTest implements Runnable{static final CountDownLatch end = new CountDownLatch(10);static final myTest test = new myTest();public static void main(String[] args) throws InterruptedException {ExecutorService executorService = Executors.newFixedThreadPool(10);for(int i=0; i<20; i++) {executorService.submit(test);}// 等待所有线程就绪end.await();System.out.println("开始");executorService.shutdown();}@Overridepublic void run() {try {long startTime = System.currentTimeMillis();Thread.sleep(new Random().nextInt(10)*100);long endTime = System.currentTimeMillis();System.out.println("共执行 "+ (endTime-startTime) + " ms");end.countDown();} catch (InterruptedException e) {throw new RuntimeException(e);}}
}

CyclicBarrier 循环栅栏

 CyclicBarrier可以重复被利用,而CountDownLatch不行。
 CyclicBarrier正如它的名字一样,循环栅栏,栅栏是一个阻挡别人进入的障碍物,CyclicBarrier和CountDownLatch一样有一个计数器,不过CountDownLatch的计数器被定义了之后就只能被一直减少,最后减少到0时,完全结束,而CyclicBarrier的计数器则是从0开始增加,直到指定数值时开始放行,然后计数器归零,并等待下一波线程的访问

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;public class myTest implements Runnable{static final CyclicBarrier end = new CyclicBarrier(5);static final myTest test = new myTest();public static void main(String[] args) throws InterruptedException {ExecutorService executorService = Executors.newFixedThreadPool(20);for(int i=0; i<20; i++) {executorService.submit(test);}executorService.shutdown();}@Overridepublic void run() {try {long startTime = System.currentTimeMillis();Thread.sleep(new Random().nextInt(10)*100);end.await();System.out.println(Thread.currentThread().getId()+"集合完成");end.await();long endTime = System.currentTimeMillis();System.out.println(Thread.currentThread().getId() + " 执行完毕: "+ endTime + " ms");} catch (InterruptedException e) {throw new RuntimeException(e);} catch (BrokenBarrierException e) {throw new RuntimeException(e);}}
}

这篇关于【Java并发编程十】同步控制二的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/408774

相关文章

Spring Boot 2.7.8 集成 Thymeleaf的最佳实践与常见问题讨论

《SpringBoot2.7.8集成Thymeleaf的最佳实践与常见问题讨论》本文详细介绍了如何将SpringBoot2.7.8与Thymeleaf集成,从项目依赖到配置文件设置,再到控制器... 目录前言一、如何构建SpringBoot应用1、项目依赖 (pom.XML)2、控制器类3、Thymelea

SpringBoot项目jar依赖问题报错解析

《SpringBoot项目jar依赖问题报错解析》本文主要介绍了SpringBoot项目中常见的依赖错误类型、报错内容及解决方法,依赖冲突包括类找不到、方法找不到、类型转换异常等,本文给大家介绍的非常... 目录常见依赖错误类型及报错内容1. 依赖冲突类错误(1) ClassNotFoundExceptio

springboot控制bean的创建顺序

《springboot控制bean的创建顺序》本文主要介绍了spring-boot控制bean的创建顺序,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随... 目录1、order注解(不一定有效)2、dependsOn注解(有效)3、提前将bean注册为Bea

Java中的ConcurrentBitSet使用小结

《Java中的ConcurrentBitSet使用小结》本文主要介绍了Java中的ConcurrentBitSet使用小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录一、核心澄清:Java标准库无内置ConcurrentBitSet二、推荐方案:Eclipse

java中的Supplier接口解析

《java中的Supplier接口解析》Java8引入的Supplier接口是一个无参数函数式接口,通过get()方法延迟计算结果,它适用于按需生成场景,下面就来介绍一下如何使用,感兴趣的可以了解一下... 目录1. 接口定义与核心方法2. 典型使用场景场景1:延迟初始化(Lazy Initializati

Java中ScopeValue的使用小结

《Java中ScopeValue的使用小结》Java21引入的ScopedValue是一种作用域内共享不可变数据的预览API,本文就来详细介绍一下Java中ScopeValue的使用小结,感兴趣的可以... 目录一、Java ScopedValue(作用域值)详解1. 定义与背景2. 核心特性3. 使用方法

spring中Interceptor的使用小结

《spring中Interceptor的使用小结》SpringInterceptor是SpringMVC提供的一种机制,用于在请求处理的不同阶段插入自定义逻辑,通过实现HandlerIntercept... 目录一、Interceptor 的核心概念二、Interceptor 的创建与配置三、拦截器的执行顺

Python中Tkinter GUI编程详细教程

《Python中TkinterGUI编程详细教程》Tkinter作为Python编程语言中构建GUI的一个重要组件,其教程对于任何希望将Python应用到实际编程中的开发者来说都是宝贵的资源,这篇文... 目录前言1. Tkinter 简介2. 第一个 Tkinter 程序3. 窗口和基础组件3.1 创建窗

Java中Map的五种遍历方式实现与对比

《Java中Map的五种遍历方式实现与对比》其实Map遍历藏着多种玩法,有的优雅简洁,有的性能拉满,今天咱们盘一盘这些进阶偏基础的遍历方式,告别重复又臃肿的代码,感兴趣的小伙伴可以了解下... 目录一、先搞懂:Map遍历的核心目标二、几种遍历方式的对比1. 传统EntrySet遍历(最通用)2. Lambd

Spring Boot 中 RestTemplate 的核心用法指南

《SpringBoot中RestTemplate的核心用法指南》本文详细介绍了RestTemplate的使用,包括基础用法、进阶配置技巧、实战案例以及最佳实践建议,通过一个腾讯地图路线规划的案... 目录一、环境准备二、基础用法全解析1. GET 请求的三种姿势2. POST 请求深度实践三、进阶配置技巧1