首页 文章 精选 留言 我的

精选列表

搜索[并发],共10000篇文章
优秀的个人博客,低调大师

实现高并发更轻松!这个编程语言竟然超过了Java...

相信有的同学看到这个标题就猜到我说的是哪个编程语言了,它就是由Google推出的Golang语言,以下是我与Golang的故事。 初识 Golang 我第一次接触 Golang 是在2014年,当时在猎豹工作,换了一个新的项目组,他们正在把基于 Java 写的核心业务用 Golang 重构一遍。 也是借着这个项目的契机,我开始学 Golang 。其实工作之后我一直在用动态语言,而开始用 Golang 这种静态语言之后,给我的编程思想带来了冲击和震撼,不夸张的说,有一种打开了另一扇窗的感觉。 如果你之前写的是 Java,就能一下感受到 Golang 的优越感了,因为 Golang 的语法更简洁、有函数式编程的特性,又不像 Java 做 OOP 那么复杂,Golang 实现 OOP 非常轻量,上手更容易,而且 Golang 非常容易的就能使

优秀的个人博客,低调大师

LiveVideoStackCon讲师热身分享 ( 十二 ) —— 微博短视频高并发架构

LiveVideoStackCon 2018音视频技术大会是每年的多媒体技术人的盛宴,为了让参会者与大会讲师更多互动交流,我们推出了LiveVideoStackCon讲师热身分享第一季,在每周四晚19:30,邀请1名大会讲师进行线上分享技术干货,解答热点问题。你可以通过以下方式参与: 关注LiveVideoStack公众号【livevideostack】 回复“热身”,即可获得进入直播群的方式 9月13日 19:30,我们将邀请新浪微博视频平台资深架构师刘志勇进行第十二期分享。本次分享刘志勇将从设计及服务可用性方面,介绍微博短视频在架构与核心缓存上的思考,以及服务的高可用保障及容灾体系的建设。 分享过程中,参与抽奖活动,更有机会获得: 10月19-20日在北京举行的LiveVideoStackCon 2018音视频技术大会五折门票。

优秀的个人博客,低调大师

Java高并发秒杀Api-业务分析与DAO层构建2

章节目录 DAO 设计编码 数据库设计与编码 DAO层实体和接口编码 基于mybatis实现DAO理论 基于mybatis实现DAO接口-1 mybatis整合Spring DAO层编码解析 Dao 设计编码 1.pom.xml 引入项目依赖的包 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.seckill</groupId> <artifactId>seckill</artifactId> <packaging>war</packaging> <version>1.0</version> <name>seckill Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <!--使用注解方式运行junit--> <version>4.11</version> <scope>test</scope> </dependency> <!--补全项目依赖--> <!--日志--> <!--1.日志 java日志,slf4j,log4j,logback,common-logging--> <!--2. slf4j 是规范、接口 日志实现 log4j,logback,common-logging 使用slf4j+logback --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.12</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.1.2</version> </dependency> <!--实现slf4j接口并实现,直接通过slf4j来进行日志记录--> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.2</version> </dependency> <!--数据库依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> <scope>runtime</scope> </dependency> <!--数据库连接池--> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <!--dao层依赖:MyBatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <!--mybatis自身实现的spring依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.3</version> </dependency> <!--servlet web相关依赖--> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!--end java web 相关依赖--> <!--spring 依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.7.RELEASE</version> </dependency> <!--spring dao层依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.1.7.RELEASE</version> </dependency> <!--spring 声明式事务--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.1.7.RELEASE</version> </dependency> <!--spring web 相关依赖 servlet容器加载spring ioc spring aop 启动spring 的工厂--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.1.7.RELEASE</version> </dependency> <!--junit相关依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.1.7.RELEASE</version> </dependency> </dependencies> <build> <finalName>seckill</finalName> </build> </project> 2.数据库设计与编码 数据库脚本如下所示: --数据库初始化脚本 --创建数据库 CREATE DATABASE seckill; --使用数据库 use seckill; --创建秒杀库存表 CREATE TABLE seckill( `seckill_id` bigint not null AUTO_INCREMENT COMMENT '商品库存id', `name` VARCHAR (120) not null COMMENT '商品名称', `stock` int not null COMMENT '库存数量', `start_time` TIMESTAMP NOT NULL COMMENT '秒杀开始时间', `end_time` TIMESTAMP NOT NULL COMMENT '秒杀结束时间', `create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', PRIMARY KEY (seckill_id), key idx_start_time(start_time), key idx_end_time(end_time), key idx_create_time(create_time) ) ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8 COMMENT='秒杀库存表'; --初始化数据 INSERT INTO seckill(name,stock,start_time,end_time) VALUES ('1000元秒杀iphone x','100','2018-05-04 00:00:00','2018-05-05 00:00:00'), ('500元秒杀ipad x','200','2018-05-04 00:00:00','2018-05-05 00:00:00'), ('300元秒杀小米4','300','2018-05-04 00:00:00','2018-05-05 00:00:00'), ('200元秒杀小米note','400','2018-05-04 00:00:00','2018-05-05 00:00:00'); --秒杀成功明细表 CREATE TABLE success_killed( `seckill_id` bigint NOT NULL COMMENT '秒杀商品id', `user_phone` VARCHAR(11) NOT NULL COMMENT '用户手机号', `state` tinyint NOT NULL DEFAULT -1 COMMENT '状态标志:-1:无效 0:成功 1:已付款', `create_time` TIMESTAMP NOT NULL COMMENT '创建时间', PRIMARY KEY (seckill_id,user_phone),/*联合主键*/ key idx_create_time(create_time) ) ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8 COMMENT='秒杀成功明细表'; --连接数据库的控制台 mysql -u root -p 3.DAO层实体与接口编码 数据库与实体类映射 3.1MyBatis 实现DAO接口的方式 Mapper自动实现DAO接口 sql直接编写,注解sql(sql更改,原代码需要重新编译),xml方式,单独更新sql,源文件不需要重新编译。 API 编程方式自动实现DAO 接口 3.2 基于mybatis实现DAO接口-1 全局mybatis-conf.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!--配置全局属性--> <configuration> <settings> <!-- changes from the defaults for testing --> <setting name="cacheEnabled" value="false" /> <!--使用jdbc 的getGeneratedKeys 获取数据库自增主键值--> <setting name="useGeneratedKeys" value="true" /> <!--使用列别名 替换列名 默认true 复制到对应的entity属性中 select name as tile from table --> <setting name="useColumnLable" value="true"/> <!--开启驼峰命名转化--> <setting name="mapUnderscoreCameCase" value="true"/> <!--REUSE 执行器会重用预处理语句--> <setting name="defaultExecutorType" value="REUSE" /> </settings> </configuration> SecKillDao.xml编写 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="org.seckill.dao.SecKillDao"> <!--目的:为DAO方法提供SQL语句配置 parameter-type不用给 #与$的区别 预编译 1.#{} 解析为一个 JDBC 预编译语句(prepared statement)的参数标记符。 会被解析为 ?占位符 动态SQL-会对SQL进行动态解析,解析为一个BoundSql对象 变量替换 2.${} 仅仅为一个纯粹的 string 替换,在动态 SQL 解析阶段将会进行变量替换 3.#{}的变量的替换是在 DBMS 中。 4.${} 在预编译之前已经被变量替换了,这会存在 sql 注入问题 5.表名是不能带''号的,所以使用${} 防止出现变量替换后表名带'' --> <update id="reduceStock"> <!--具体sql--> UPDATE seckill SET stock = stock - 1 WHERE seckill_id = #{secKillId} AND start_time <![CDATA[<=]]> #{killTime} AND end_time >= #{killTime} and stock > 0 </update> <select id="queryById" resultType="SecKill" parameterType="long"> SELECT seckill_id as seckillId,name,stock,start_time,end_time,create_time from seckill where seckill_id = #{secKillId} </select> <select id="queryAll" resultType="SecKill" parameterType="int"> SELECT seckill_id as seckillId,name,stock,start_time,end_time,create_time from seckill order by create_time desc limit #{offset},${limit} </select> </mapper> SuccessKilledDao.xml 编写 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="org.seckill.dao.SuccessKilledDao"> <insert id="insertSuccessKilled" > <!--如果出现重复,主键冲突,直接产生一个错误--> INSERT ignore INTO success_killed(seckill_id,user_phone) VALUES (#{secKillId},#{userPhone}) </insert> <select id="queryByIdWithSecKill" resultType="SuccessKilled" > <!--根据id查询SuccessKilled并携带SecKill实体--> <!--如何告诉mybatis 把结果映射到SuccessKilled的同时映射secKill 属性--> <!--可以自由控制SQL 优化等--> SELECT sk.seckill_id, sk.user_phone, sk.create_time, sk.state, sc.seckill_id as "secKill.seckill_id", sc.name as "secKill.name", sc.stock as "secKill.stock", sc.start_time as "secKill.start_time", sc.end_time as "sceKill.end_time", sc.create_time as "secKill.create_time" FROM success_killed sk INNER JOIN seckill sc on sk.seckill_id = sc.seckill_id WHERE sk.seckill_id = #{secKillId} </select> </mapper> entity实体层实现-SecKill、SuccessKilled package org.seckill.domain; import java.util.Date; /** * 秒杀-库存表 entity */ public class SecKill { private long seckillId; //秒杀-商品id private String name; //秒杀-商品名字 private int stock; //秒杀-商品库存 private Date startTime; //秒杀-开始时间 private Date endTime; //秒杀-结束时间 private Date createTime; //秒杀-商品新建时间 public long getSeckillId() { return seckillId; } public void setSeckillId(long seckillId) { this.seckillId = seckillId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getStock() { return stock; } public void setStock(int stock) { this.stock = stock; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { return "SecKill{" + "seckillId=" + seckillId + ", name='" + name + '\'' + ", stock=" + stock + ", startTime=" + startTime + ", endTime=" + endTime + ", createTime=" + createTime + '}'; } } package org.seckill.domain; import java.util.Date; /** * 成功秒杀明细表-SuccessKilled */ public class SuccessKilled { private long secKillId; //秒杀-成功的商品id private String userPhone; //秒杀-成功的用户手机号 private short state; //秒杀-明细状态 private Date createTime; //秒杀-秒杀成功的时间 //one(被秒杀商品)-to-many(秒杀记录) private SecKill secKill; public long getSecKillId() { return secKillId; } public void setSecKillId(long secKillId) { this.secKillId = secKillId; } public String getUserPhone() { return userPhone; } public void setUserPhone(String userPhone) { this.userPhone = userPhone; } public short getState() { return state; } public void setState(short state) { this.state = state; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public SecKill getSecKill() { return secKill; } public void setSecKill(SecKill secKill) { this.secKill = secKill; } @Override public String toString() { return "SuccessKilled{" + "secKillId=" + secKillId + ", userPhone='" + userPhone + '\'' + ", state=" + state + ", createTime=" + createTime + '}'; } } DAO层接口功能声明-SecKillDao、SuccessKilledDao package org.seckill.dao; import org.seckill.domain.SecKill; import java.util.Date; import java.util.List; /** * 常用的操作 */ public interface SecKillDao { /** * 功能:减库存 * @param secKillId * @param killTime create_time? * @return 如果影响行数>1,表示更新的记录行数 */ int reduceStock(long secKillId,Date killTime); /** * 根据秒杀商品id查询秒杀商品详情 * @param secKillId * @return */ SecKill queryById(long secKillId); /** * 根据偏移量查询秒杀商品列表, * @param offset * @param limit * @return */ List<SecKill> queryAll(int offset,int limit); } package org.seckill.dao; import org.seckill.domain.SuccessKilled; public interface SuccessKilledDao { /** * 功能:新增用户秒杀明细 * @param secKillId * @param userPhone * @return 插入的行数,禁止插入表示插入失败 则返回0 */ int insertSuccessKilled(long secKillId,long userPhone); /** * 功能:根据明细id查询具体的秒杀明细并携带秒杀商品对象 * @param secKillId * @return */ SuccessKilled queryByIdWithSecKill(long secKillId); } MyBatis整合Spring 整合的目标: 更少的编码 更少的配置 足够的灵活性1.mybatis优点 更少的编码、只写接口、不写实现 2.DAO层接口声明能显示说明很多事情 轻量级显式接口声明 更少的配置-别名 image.png 使用spring 提供的package-scan 扫描实体包下的所有实体类。可以简写resultType 更少的配置-配置扫描 单独使用mybatis的场景下,配置文件扫描方式 <mapper resource="mapper/SecKillDao.xml">.... 使用spring 整合 mybatis 自动扫描配置文件,采用通配符的方式。 自动实现DAO接口,DAO接口的实现类是自动注入至Spring 容器 足够的灵活性 image.png 5.DAO层接口设计与SQL编写的反思 DAO - data access object 数据访问层的简称 这一层我们主要做的是核心数据操作的接口声明,以及SQL编写,并没有涉及到Service 业务逻辑层代码的编写。这样做的好处是什么呢? 主要有以下三点 代码分层,DAO层只关注于核心数据操作的接口声明&SQL编写 代码和SQL的分离,方便代码review 业务逻辑层主要做事务控制、事务中完成DAO层的代码组合与拼接。每一层都可以做单元测试。 接下来详解mybatis 与 spring 整合编码的过程

优秀的个人博客,低调大师

Java高并发秒杀Api-业务分析与DAO层构建3

章节目录 mybatis与spring整合过程 spring-dao.xml 配置 junit4 单元测试 1.mybatis与spring整合过程 1.1 spring-dao.xml 配置 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--配置整合mybatis--> <!--1:配置数据库相关参数--> <!-- 1:配置数据库相关参数properties的属性:${url} --> <context:property-placeholder location="classpath:jdbc.properties"/> <!--2.数据库连接池配置--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 配置连接池属性--> <property name="driverClass" value="${driver}" /> <property name="jdbcUrl" value="${url}" /> <property name="user" value="${username}" /> <property name="password" value="${password}" /> <!-- c3p0连接池的私有属性--> <property name="maxPoolSize" value="30" /> <property name="minPoolSize" value="10" /> <!-- 关闭连接后不自动commit--> <property name="autoCommitOnClose" value="false" /> <!-- 获取连接超时时间 30个连接用完--> <property name="checkoutTimeout" value="1000" /> <!-- 当获取连接失败重试次数--> <property name="acquireRetryAttempts" value="2" /> </bean> <!-- 约定大于配置--> <!-- 3:配置SqlSessionFactory对象--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据库连接池--> <property name="dataSource" ref="dataSource" /> <!-- 配置MyBatis全局配置文件:mybatis-config.xml--> <property name="configLocation" value="classpath:mybatis-config.xml" /> <!-- 扫描entity包 使用别名--> <property name="typeAliasesPackage" value="org.seckill.domain" /> <!-- 扫描sql配置文件;mapper需要的xml文件--> <property name="mapperLocations" value="classpath:mapper/*.xml" /> </bean> <!--配置扫描Dao接口包,动态实现Dao接口 mapper 代理,并注入到Spring容器中 MapperScannerConfigurer--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--注入sqlSessionFactory,懒加载,用到的时候才加载--> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> <!--给出扫描DAO接口包--> <property name="basePackage" value="org.seckill.dao"></property> </bean> </beans> 2.junit 单元测试 SecKillDaoTest.java - 测试秒杀 package org.seckill.dao; import org.junit.Test; import org.junit.runner.RunWith; import org.seckill.domain.SecKill; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Date; import java.util.List; /** * 配置spring 与 junit 启动时加载Spring IOC容器 * spring-test,junit整合 * 告诉junit Spring配置文件位置 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:spring/spring-dao.xml"}) public class SecKillDaoTest { //注入Dao类实现 @Autowired private SecKillDao secKillDao; @Test public void queryById() throws Exception { long id = 1000; SecKill secKill = secKillDao.queryById(id); System.out.println(secKill.getName()); System.out.println(secKill); /** * 1000元秒杀iphone x SecKill{seckillId=1000, name='1000元秒杀iphone x', stock=100, startTime=Fri May 04 00:00:00 CST 2018, endTime=Sat May 05 00:00:00 CST 2018, createTime=Sat May 05 00:05:03 CST 2018 } */ } /** * @throws Exception */ @Test public void queryAll() throws Exception { // queryAll(offset,limit)->queryAll(arg0,arg1) List<SecKill> secKillList = secKillDao.queryAll(0, 100); for (SecKill secKill : secKillList) { System.out.println(secKill); } /** * SecKill{seckillId=1000, name='1000元秒杀iphone x', stock=100, startTime=Fri May 04 00:00:00 CST 2018, endTime=Sat May 05 00:00:00 CST 2018, createTime=Sat May 05 00:05:03 CST 2018} SecKill{seckillId=1001, name='500元秒杀ipad x', stock=200, startTime=Fri May 04 00:00:00 CST 2018, endTime=Sat May 05 00:00:00 CST 2018, createTime=Sat May 05 00:05:03 CST 2018} SecKill{seckillId=1002, name='300元秒杀小米4', stock=300, startTime=Fri May 04 00:00:00 CST 2018, endTime=Sat May 05 00:00:00 CST 2018, createTime=Sat May 05 00:05:03 CST 2018} SecKill{seckillId=1003, name='200元秒杀小米note', stock=400, startTime=Fri May 04 00:00:00 CST 2018, endTime=Sat May 05 00:00:00 CST 2018, createTime=Sat May 05 00:05:03 CST 2018} */ } @Test public void reduceStock() throws Exception { Date killTime = new Date(); int updateCount = secKillDao.reduceStock(1000L, killTime); System.out.println(updateCount); } } 测试秒杀明细 package org.seckill.dao; import org.junit.Test; import org.junit.runner.RunWith; import org.seckill.domain.SuccessKilled; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:spring/spring-dao.xml") public class SuccessKilledDaoTest { @Autowired private SuccessKilledDao successKilledDao; @Test public void insertSuccessKilled() throws Exception { int successCount = successKilledDao.insertSuccessKilled(1001L, "15300815999"); System.out.println("insertCount=" + successCount); } @Test public void queryByIdWithSecKill() throws Exception { //1个用户只能查询到属于自己的一个秒杀明细 long id = 1001L; String phone = "15300815999"; SuccessKilled successKilled = successKilledDao.queryByIdWithSecKill(id, phone); System.out.println(successKilled); } } 接下来是service 层的构建

优秀的个人博客,低调大师

Java并发编程的艺术(九)——批量获取多条线程的执行结果

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34173549/article/details/79612353 当向线程池提交callable任务后,我们可能需要一次性获取所有返回结果,有三种处理方法。 方法一:自己维护返回结果 // 创建一个线程池 ExecutorService executorService = Executors.newFixedThreadPool(10); // 存储执行结果的List List<Future<String>> results = new ArrayList<Future<String>>(); // 提交10个任务 for ( int i=0; i<10; i++ ) { Future<String> result = executorService.submit( new Callable<String>(){ public String call(){ int sleepTime = new Random().nextInt(1000); Thread.sleep(sleepTime); return "线程"+i+"睡了"+sleepTime+"秒"; } } ); // 将执行结果存入results中 results.add( result ); } // 获取10个任务的返回结果 for ( int i=0; i<10; i++ ) { // 获取包含返回结果的future对象 Future<String> future = results.get(i); // 从future中取出执行结果(若尚未返回结果,则get方法被阻塞,直到结果被返回为止) String result = future.get(); System.out.println(result); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 此方法的弊端: 需要自己创建容器维护所有的返回结果,比较麻烦; 从list中遍历的每个Future对象并不一定处于完成状态,这时调用get()方法就会被阻塞住,如果系统是设计成每个线程完成后就能根据其结果继续做后面的事,这样对于处于list后面的但是先完成的线程就会增加了额外的等待时间。 方法二:使用ExecutorService的invokeAll函数 本方法能解决第一个弊端,即并不需要自己去维护一个存储返回结果的容器。当我们需要获取线程池所有的返回结果时,只需调用invokeAll函数即可。但是,这种方式需要你自己去维护一个用于存储任务的容器。 // 创建一个线程池 ExecutorService executorService = Executors.newFixedThreadPool(10); // 创建存储任务的容器 List<Callable<String>> tasks = new ArrayList<Callable<String>>(); // 提交10个任务 for ( int i=0; i<10; i++ ) { Callable<String> task = new Callable<String>(){ public String call(){ int sleepTime = new Random().nextInt(1000); Thread.sleep(sleepTime); return "线程"+i+"睡了"+sleepTime+"秒"; } }; executorService.submit( task ); // 将task添加进任务队列 tasks.add( task ); } // 获取10个任务的返回结果 List<Future<String>> results = executorService.invokeAll( tasks ); // 输出结果 for ( int i=0; i<10; i++ ) { // 获取包含返回结果的future对象 Future<String> future = results.get(i); // 从future中取出执行结果(若尚未返回结果,则get方法被阻塞,直到结果被返回为止) String result = future.get(); System.out.println(result); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 方法三:使用CompletionService CompletionService内部维护了一个阻塞队列,只有执行完成的任务结果才会被放入该队列,这样就确保执行时间较短的任务率先被存入阻塞队列中。 ExecutorService exec = Executors.newFixedThreadPool(10); final BlockingQueue<Future<Integer>> queue = new LinkedBlockingDeque<Future<Integer>>( 10); //实例化CompletionService final CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>( exec, queue); // 提交10个任务 for ( int i=0; i<10; i++ ) { executorService.submit( new Callable<String>(){ public String call(){ int sleepTime = new Random().nextInt(1000); Thread.sleep(sleepTime); return "线程"+i+"睡了"+sleepTime+"秒"; } } ); } // 输出结果 for ( int i=0; i<10; i++ ) { // 获取包含返回结果的future对象(若整个阻塞队列中还没有一条线程返回结果,那么调用take将会被阻塞,当然你可以调用poll,不会被阻塞,若没有结果会返回null,poll和take返回正确的结果后会将该结果从队列中删除) Future<String> future = completionService.take(); // 从future中取出执行结果,这里存储的future已经拥有执行结果,get不会被阻塞 String result = future.get(); System.out.println(result); }

优秀的个人博客,低调大师

java面试-Java并发编程(九)——批量获取多条线程的执行结果

当向线程池提交callable任务后,我们可能需要一次性获取所有返回结果,有三种处理方法。 方法一:自己维护返回结果 // 创建一个线程池 ExecutorService executorService = Executors.newFixedThreadPool(10); // 存储执行结果的List List<Future<String>> results = new ArrayList<Future<String>>(); // 提交10个任务 for ( int i=0; i<10; i++ ) { Future<String> result = executorService.submit( new Callable<String>(){ public String call(){ int sleepTime = new Random().nextInt(1000); Thread.sleep(sleepTime); return "线程"+i+"睡了"+sleepTime+"秒"; } } ); // 将执行结果存入results中 results.add( result ); } // 获取10个任务的返回结果 for ( int i=0; i<10; i++ ) { // 获取包含返回结果的future对象 Future<String> future = results.get(i); // 从future中取出执行结果(若尚未返回结果,则get方法被阻塞,直到结果被返回为止) String result = future.get(); System.out.println(result); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 此方法的弊端: 需要自己创建容器维护所有的返回结果,比较麻烦; 从list中遍历的每个Future对象并不一定处于完成状态,这时调用get()方法就会被阻塞住,如果系统是设计成每个线程完成后就能根据其结果继续做后面的事,这样对于处于list后面的但是先完成的线程就会增加了额外的等待时间。 方法二:使用ExecutorService的invokeAll函数 本方法能解决第一个弊端,即并不需要自己去维护一个存储返回结果的容器。当我们需要获取线程池所有的返回结果时,只需调用invokeAll函数即可。但是,这种方式需要你自己去维护一个用于存储任务的容器。 // 创建一个线程池 ExecutorService executorService = Executors.newFixedThreadPool(10); // 创建存储任务的容器 List<Callable<String>> tasks = new ArrayList<Callable<String>>(); // 提交10个任务 for ( int i=0; i<10; i++ ) { Callable<String> task = new Callable<String>(){ public String call(){ int sleepTime = new Random().nextInt(1000); Thread.sleep(sleepTime); return "线程"+i+"睡了"+sleepTime+"秒"; } }; executorService.submit( task ); // 将task添加进任务队列 tasks.add( task ); } // 获取10个任务的返回结果 List<Future<String>> results = executorService.invokeAll( tasks ); // 输出结果 for ( int i=0; i<10; i++ ) { // 获取包含返回结果的future对象 Future<String> future = results.get(i); // 从future中取出执行结果(若尚未返回结果,则get方法被阻塞,直到结果被返回为止) String result = future.get(); System.out.println(result); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 方法三:使用CompletionService CompletionService内部维护了一个阻塞队列,只有执行完成的任务结果才会被放入该队列,这样就确保执行时间较短的任务率先被存入阻塞队列中。 ExecutorService exec = Executors.newFixedThreadPool(10); final BlockingQueue<Future<Integer>> queue = new LinkedBlockingDeque<Future<Integer>>( 10); //实例化CompletionService final CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>( exec, queue); // 提交10个任务 for ( int i=0; i<10; i++ ) { executorService.submit( new Callable<String>(){ public String call(){ int sleepTime = new Random().nextInt(1000); Thread.sleep(sleepTime); return "线程"+i+"睡了"+sleepTime+"秒"; } } ); } // 输出结果 for ( int i=0; i<10; i++ ) { // 获取包含返回结果的future对象(若整个阻塞队列中还没有一条线程返回结果,那么调用take将会被阻塞,当然你可以调用poll,不会被阻塞,若没有结果会返回null,poll和take返回正确的结果后会将该结果从队列中删除) Future<String> future = completionService.take(); // 从future中取出执行结果,这里存储的future已经拥有执行结果,get不会被阻塞 String result = future.get(); System.out.println(result); }

优秀的个人博客,低调大师

Java并发编程的艺术(八)——闭锁、同步屏障、信号量详解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34173549/article/details/79612374 1. 闭锁:CountDownLatch 1.1 使用场景 若有多条线程,其中一条线程需要等到其他所有线程准备完所需的资源后才能运行,这样的情况可以使用闭锁。 1.2 代码实现 // 初始化闭锁,并设置资源个数 CountDownLatch latch = new CountDownLatch(2); Thread t1 = new Thread( new Runnable(){ public void run(){ // 加载资源1 加载资源的代码…… // 本资源加载完后,闭锁-1 latch.countDown(); } } ).start(); Thread t2 = new Thread( new Runnable(){ public void run(){ // 加载资源2 资源加载代码…… // 本资源加载完后,闭锁-1 latch.countDown(); } } ).start(); Thread t3 = new Thread( new Runnable(){ public void run(){ // 本线程必须等待所有资源加载完后才能执行 latch.await(); // 当闭锁数量为0时,await返回,执行接下来的任务 任务代码…… } } ).start(); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 2. 同步屏障:CyclicBarrier 2.1 使用场景 若有多条线程,他们到达屏障时将会被阻塞,只有当所有线程都到达屏障时才能打开屏障,所有线程同时执行,若有这样的需求可以使用同步屏障。此外,当屏障打开的同时还能指定执行的任务。 2.2 闭锁 与 同步屏障 的区别 闭锁只会阻塞一条线程,目的是为了让该条任务线程满足条件后执行; 而同步屏障会阻塞所有线程,目的是为了让所有线程同时执行(实际上并不会同时执行,而是尽量把线程启动的时间间隔降为最少)。 2.3 代码实现 // 创建同步屏障对象,并制定需要等待的线程个数 和 打开屏障时需要执行的任务 CyclicBarrier barrier = new CyclicBarrier(3,new Runnable(){ public void run(){ //当所有线程准备完毕后触发此任务 } }); // 启动三条线程 for( int i=0; i<3; i++ ){ new Thread( new Runnable(){ public void run(){ // 等待,(每执行一次barrier.await,同步屏障数量-1,直到为0时,打开屏障) barrier.await(); // 任务 任务代码…… } } ).start(); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 3. 信号量:Semaphore 3.1 使用场景 若有m个资源,但有n条线程(n>m),因此同一时刻只能允许m条线程访问资源,此时可以使用Semaphore控制访问该资源的线程数量。 3.2 代码实现 // 创建信号量对象,并给予3个资源 Semaphore semaphore = new Semaphore(3); // 开启10条线程 for ( int i=0; i<10; i++ ) { new Thread( new Runnbale(){ public void run(){ // 获取资源,若此时资源被用光,则阻塞,直到有线程归还资源 semaphore.acquire(); // 任务代码 …… // 释放资源 semaphore.release(); } } ).start(); }

优秀的个人博客,低调大师

java面试-Java并发编程(八)——闭锁、同步屏障、信号量详解

1. 闭锁:CountDownLatch 1.1 使用场景 若有多条线程,其中一条线程需要等到其他所有线程准备完所需的资源后才能运行,这样的情况可以使用闭锁。 1.2 代码实现 // 初始化闭锁,并设置资源个数 CountDownLatch latch = new CountDownLatch(2); Thread t1 = new Thread( new Runnable(){ public void run(){ // 加载资源1 加载资源的代码…… // 本资源加载完后,闭锁-1 latch.countDown(); } } ).start(); Thread t2 = new Thread( new Runnable(){ public void run(){ // 加载资源2 资源加载代码…… // 本资源加载完后,闭锁-1 latch.countDown(); } } ).start(); Thread t3 = new Thread( new Runnable(){ public void run(){ // 本线程必须等待所有资源加载完后才能执行 latch.await(); // 当闭锁数量为0时,await返回,执行接下来的任务 任务代码…… } } ).start(); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 2. 同步屏障:CyclicBarrier 2.1 使用场景 若有多条线程,他们到达屏障时将会被阻塞,只有当所有线程都到达屏障时才能打开屏障,所有线程同时执行,若有这样的需求可以使用同步屏障。此外,当屏障打开的同时还能指定执行的任务。 2.2 闭锁 与 同步屏障 的区别 闭锁只会阻塞一条线程,目的是为了让该条任务线程满足条件后执行; 而同步屏障会阻塞所有线程,目的是为了让所有线程同时执行(实际上并不会同时执行,而是尽量把线程启动的时间间隔降为最少)。 2.3 代码实现 // 创建同步屏障对象,并制定需要等待的线程个数 和 打开屏障时需要执行的任务 CyclicBarrier barrier = new CyclicBarrier(3,new Runnable(){ public void run(){ //当所有线程准备完毕后触发此任务 } }); // 启动三条线程 for( int i=0; i<3; i++ ){ new Thread( new Runnable(){ public void run(){ // 等待,(每执行一次barrier.await,同步屏障数量-1,直到为0时,打开屏障) barrier.await(); // 任务 任务代码…… } } ).start(); } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 3. 信号量:Semaphore 3.1 使用场景 若有m个资源,但有n条线程(n>m),因此同一时刻只能允许m条线程访问资源,此时可以使用Semaphore控制访问该资源的线程数量。 3.2 代码实现 // 创建信号量对象,并给予3个资源 Semaphore semaphore = new Semaphore(3); // 开启10条线程 for ( int i=0; i<10; i++ ) { new Thread( new Runnbale(){ public void run(){ // 获取资源,若此时资源被用光,则阻塞,直到有线程归还资源 semaphore.acquire(); // 任务代码 …… // 释放资源 semaphore.release(); } } ).start(); }

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

用户登录
用户注册
修改密码
忘记密码