当前位置:网站首页>解决线程并发安全问题
解决线程并发安全问题
2022-06-25 22:13:00 【大魔王的日常Log】
package cn.wlt.tickets;
/**
*
* @作者: CarryWang
* @描述: 买票窗口 100张票
*
*/
public class SaleTicket extends Thread{
private String name;
/**
* 100张票数共享的数据 属于类的属性
*/
private static int tickets=100;
//同步锁对象
private static Object obj=new Object();
public SaleTicket(String name) {
super(name);
this.name = name;
}
@Override
public void run() {
while(true){
/*
* 锁 synchronized (name) 这个name对象一定得是共享对象
* 同步代码块
*/
synchronized (obj) {
if(tickets>0){
try {
//线程休息10毫秒
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.getName()+"正在卖第"+tickets--+"张票");
}else{
System.out.println("票已经售完");
break;
}
}
}
}
}
测试代码:
package cn.wlt.tickets;
import org.junit.Test;
public class TicketTest {
public static void main(String[] args) {
SaleTicket st1=new SaleTicket("窗口1");
SaleTicket st2=new SaleTicket("窗口2");
SaleTicket st3=new SaleTicket("窗口3");
SaleTicket st4=new SaleTicket("窗口4");
st1.start();
st2.start();
st3.start();
st4.start();
}
}
边栏推荐
- 6. common instructions (upper) v-cloak, v-once, v-pre
- Literature research (IV): Hourly building power consumption prediction based on case-based reasoning, Ann and PCA
- JS中常用知识点
- About Simple Data Visualization
- Number array de duplication in JS
- 2021-04-28
- 利用VBScript连接mysql数据库_过路老熊_新浪博客
- 10.2.2、Kylin_kylin的安装,上传解压,验证环境变量,启动,访问
- Recommended system design
- 《网络是怎么样连接的》读书笔记 - 集线器、路由器和路由器(三)
猜你喜欢

10.4.1、数据中台

关于scrapy爬虫时,由spider文件将item传递到管道的方法注意事项

(Reprint) visual explanation of processes and threads

About the solution to prompt modulenotfounderror: no module named'pymongo 'when running the scratch project

数组常用的一些操作方法

ValueError: color kwarg must have one color per data set. 9 data sets and 1 colors were provided解决

86.(cesium篇)cesium叠加面接收阴影效果(gltf模型)

Thrift入门学习

猕猴桃酵素的功效_过路老熊_新浪博客

STEP7主站与远程I/O组网_过路老熊_新浪博客
随机推荐
Keil compilation run error, missing error: # 5: # includecore_ cm3.h_ Old bear passing by_ Sina blog
js实现输入开始时间和结束时间,输出其中包含多少个季,并且把对应年月打印出来
如何配置SQL Server 2008管理器_过路老熊_新浪博客
Common methods of object class
Redis之内存淘汰机制
SMT贴片加工PCBA板清洗注意事项
Joint simulation of STEP7 and WinCC_ Old bear passing by_ Sina blog
ValueError: color kwarg must have one color per data set. 9 data sets and 1 colors were provided解决
Transformation of communication protocol between Siemens S7-200PLC and Danfoss inverter_ Old bear passing by_ Sina blog
Alipay payment interface sandbox environment test and integration into an SSM e-commerce project
Network protocol: detailed explanation of redis protocol
用ES5的方式实现const
Backup restore of xtrabackup
Literature research (III): overview of data-driven building energy consumption prediction models
Stop eating vitamin C tablets. These six fruits have the highest vitamin C content
Tensorflow中CSV文件数据读取
利用swiper实现轮播图
Summary of c++ references and pointers
About Simple Data Visualization
The role of iomanip header file in actual combat