1 Star 0 Fork 0

yolovf/thread

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
SellTicketsTestTwo.java 1.79 KB
一键复制 编辑 原始数据 按行查看 历史
yolovf 提交于 2023-12-08 12:57 . 线程小案例
package com.yolovf.knowledge.test.thread.test;
/**
* @Author: xbcao
* @Description: TODO
* @Date: 2023/11/29 17:52:11
* @Since: jdk1.8
* @Version: 1.0
*/
public class SellTicketsTestTwo {
public static void main(String[] args) {
ThreadRunnableTwo threadRunnable = new ThreadRunnableTwo();
Thread t1 = new Thread(threadRunnable);
t1.setName("pdd");
Thread t2 = new Thread(threadRunnable);
t2.setName("jd");
Thread t3 = new Thread(threadRunnable);
t3.setName("tb");
t1.start();
t2.start();
t3.start();
}
}
class ThreadRunnableTwo implements Runnable{
private int ticketsNum = 0;
private int pddTickets = 0; //pdd最多购买4张
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (ThreadRunnableTwo.class) {
if (ticketsNum == 30) {
break;
}else {
if ("pdd".equals(Thread.currentThread().getName())) {
if (pddTickets >= 4) {
System.out.println("pdd已卖完");
break;
} else {
pddTickets++;
System.out.println(Thread.currentThread().getName() + "--->" + (++ticketsNum) + "张票");
}
} else {
System.out.println(Thread.currentThread().getName() + "正在出售第" + (++ticketsNum) + "张票");
}
}
}
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yolovf/thread.git
git@gitee.com:yolovf/thread.git
yolovf
thread
thread
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385