当前位置:网站首页>解决线程并发安全问题
解决线程并发安全问题
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();
}
}
边栏推荐
猜你喜欢

Explain in detail the three types of local variables, global variables and static variables

《网络是怎么样连接的》读书笔记 - 集线器、路由器和路由器(三)

SSM integrated learning notes (mainly ideas)

10.4.1、數據中臺
![Bit compressor [Blue Bridge Cup training]](/img/d5/231d20bf4104cc2619b2a4f19b605c.png)
Bit compressor [Blue Bridge Cup training]

Redis之跳跃表

Literature research (I): hourly energy consumption prediction of office buildings based on integrated learning and energy consumption pattern classification

Final and static
![搜索旋转数组II[抽象二分练习]](/img/db/3ea01cf1ad8446a7007891ef1d8e7f.png)
搜索旋转数组II[抽象二分练习]

Let's talk about string today
随机推荐
Detailed explanation of redis
Shredding Company poj 1416
SMT葡萄球现象解决办法
10.4.1、數據中臺
数组常用的一些操作方法
10.4.1 data console
Recherche documentaire (3): examen des modèles de prévision de la consommation d'énergie des bâtiments fondés sur les données
Topic36——53. Maximum subarray and
SMT贴片加工PCBA板清洗注意事项
Literature research (III): overview of data-driven building energy consumption prediction models
Redis之内存淘汰机制
关于scrapy爬虫时,由spider文件将item传递到管道的方法注意事项
寻找翻转数组的最小值[抽象二分]
用frp搭建云电脑
DHCP review
Bit compressor [Blue Bridge Cup training]
Keil compilation run error, missing error: # 5: # includecore_ cm3.h_ Old bear passing by_ Sina blog
如何配置SQL Server 2008管理器_过路老熊_新浪博客
Efficacy of kiwi fruit enzyme_ Old bear passing by_ Sina blog
dhcp复习