Java 多线程初探索之模拟车站多窗口售票

2024-08-24 23:08

本文主要是介绍Java 多线程初探索之模拟车站多窗口售票,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

欢迎各路大神批评指正

---------------------------------->分割线<---------------------------------

阅读之前,你应该了解:

1.java多线程的两种写法

2.线程变量

3.Java线程工作内存与主内存变量交换过程


思考:模拟一个车站多窗口售票程序,必须满足以下条件:(1)必须多个窗口进行售票(2)票不可多卖,比如有20张票,不能卖出21张

开始写一个售票程序:

public class Test {public static void main(String[] args) {for(int i = 1;i <= 10;i++){new Thread(new MyThread("窗口"+i)).start();System.out.println("线程"+i+"启动了");}}
}
class MyThread implements Runnable{private String name;//当前售票窗口编号private static final int total = 20;//总票数public MyThread(String name) {super();this.name = name;}public MyThread(){super();}@Overridepublic synchronized void run() {for (int i = 1; i <= total; i++) {System.out.println(this.name + "卖出了票" + current);try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}
}

看起来似乎没什么毛病,执行一下:

这一看就有问题,为什么我用了同步,依旧是出问题了。肯定是同步用的不对,考虑到卖了哪张票应该是所有窗口都需要知道的,比如窗口1卖了编号为1的票,窗口2就应该知道1号票被卖出去了,针对这个问题,我们做一下改进:

public class Test {public static void main(String[] args) {for(int i = 1;i <= 10;i++){new Thread(new MyThread("窗口"+i)).start();System.out.println("线程"+i+"启动了");}}
}
class MyThread implements Runnable{private String name;//售票窗口名称private static final int total = 20;//总票数private static int current = 1;//当前应该卖的票的编号public MyThread(String name) {super();this.name = name;}public MyThread(){super();}@Overridepublic synchronized void run() {for (; current <= total; current++) {System.out.println(this.name + "卖出了票" + current);try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}
}

,执行一下:


我去,还是有问题,这错误到底是在哪??????????

其实这个问题是同步出现了问题,在Test类的main函数中,我们启动的10个线程,每个线程都有一个MyThread类,在执行run方法的时候,每个线程都去获得自己MyThread类的锁,这个只要不出什么其他问题,都会获取到。这样10个线程相互独立,都获取自己线程内的锁,还有锁竞争吗?没有竞争还需要同步吗?很显然,问题出现在了10个线程竞争的不是同一个锁上面了,那么我们来改进这个问题,想办法让线程竞争同一个锁,于是:

public class Test {public static void main(String[] args) {for(int i = 1;i <= 10;i++){new Thread(new MyThread("窗口"+i)).start();System.out.println("线程"+i+"启动了");}}
}
class MyThread implements Runnable{private String name;//售票窗口名称private static final int total = 20;//总票数private static int current = 1;//当前应该卖的票的编号public static final String lock = "我是锁";//静态类,让线程竞争这个类的锁//因为在内存中,MyThread.lock只有一个,所以竞争这个类的锁public MyThread(String name) {super();this.name = name;}public MyThread(){super();}@Overridepublic void run() {while (current <= total) {synchronized (MyThread.lock) {//1.售票的过程是原子的,不可分割的,//2.多个线程会MyThread.lock这个类的锁,这次锁只有一个,会发生竞争System.out.println(this.name + "卖出了票" + current);try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}current++;}}}
}
执行:

这次看起来问题不大,可是:


这就很尴尬了,本来就20张票,愣生生的卖出去29张

鉴于这种卖超的问题,我们加个限制条件应该就可以了:

public class Test {public static void main(String[] args) {for(int i = 1;i <= 10;i++){new Thread(new MyThread("窗口"+i)).start();System.out.println("线程"+i+"启动了");}}
}
class MyThread implements Runnable{private String name;//售票窗口名称private static final int total = 20;//总票数private static int current = 1;//当前应该卖的票的编号public static final String lock = "我是锁";//静态类,让线程竞争这个类的锁//因为在内存中,MyThread.lock只有一个,所以竞争这个类的锁public MyThread(String name) {super();this.name = name;}public MyThread(){super();}@Overridepublic void run() {while (current <= total) {synchronized (MyThread.lock) {//1.售票的过程是原子的,不可分割的,//2.多个线程会MyThread.lock这个类的锁,这次锁只有一个,会发生竞争if(current > total){System.out.println("票卖完了");break;}System.out.println(this.name + "卖出了票" + current);try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}current++;}}}
}

执行:


看起来应该没啥问题了。思考下:刚才为什么会卖超?,我输出了一下卖超情况的票的编号,代码如下:

public class Test {public static void main(String[] args) {for(int i = 1;i <= 10;i++){new Thread(new MyThread("窗口"+i)).start();System.out.println("线程"+i+"启动了");}}
}
class MyThread implements Runnable{private String name;//售票窗口名称private static final int total = 20;//总票数private static int current = 1;//当前应该卖的票的编号public static final String lock = "我是锁";//静态类,让线程竞争这个类的锁//因为在内存中,MyThread.lock只有一个,所以竞争这个类的锁public MyThread(String name) {super();this.name = name;}public MyThread(){super();}@Overridepublic void run() {while (current <= total) {synchronized (MyThread.lock) {//1.售票的过程是原子的,不可分割的,//2.多个线程会MyThread.lock这个类的锁,这次锁只有一个,会发生竞争if(current > total){System.out.println("票卖完了,当前票的编号为:"+current);//break;}System.out.println(this.name + "卖出了票" + current);try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}current++;}}}
}

执行:

很明显,除了卖出票20的那个窗口(线程),后面每个窗口(线程)都多卖票了,而且每个多卖一张。这是为什么?

猜想:

线程在执行到

这个地方的时候,current变量为线程私有变量,假设线程1执行到这里,它的线程内变量current(这个线程内的current是从内存中拷贝过来的)是20,符合条件,而另外一个线程,我们认为这个线程是线程2,它的变量current是19,因为线程1拿到了锁,线程2被阻塞,希望拿到锁。线程1继续执行,卖完票20之后,把current++,变为21并且释放锁的时候把current同步到内存,此时内存的current为21。线程2拿到了锁,开始执行卖票,因为current被线程1改成了21,所以,线程2 把票21卖出了,此时票卖超了。综上所述,线程实在while(current <= total)后开始竞争锁,因为判断的时候这个while(current <= total)是成立的,所以会执行进while的范围内,而在竞争锁的时候,其他窗口(线程)已经

把票卖完,而当前线程已经执行进了while,不会再判断,于是,票卖超了,我们加上if(current > total)这个判断,就是去掉在等待锁的过程中,其他窗口(线程)把票卖完的情况。

如有不妥之处,欢迎批评指正。

这篇关于Java 多线程初探索之模拟车站多窗口售票的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。

java.sql.SQLTransientConnectionException连接超时异常原因及解决方案

《java.sql.SQLTransientConnectionException连接超时异常原因及解决方案》:本文主要介绍java.sql.SQLTransientConnectionExcep... 目录一、引言二、异常信息分析三、可能的原因3.1 连接池配置不合理3.2 数据库负载过高3.3 连接泄漏