1 Star 0 Fork 0

yolovf/thread

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
VipTickets.java 1.64 KB
一键复制 编辑 原始数据 按行查看 历史
yolovf 提交于 2023-12-08 12:57 . 线程小案例
package com.yolovf.knowledge.test.thread.test;
import lombok.SneakyThrows;
/**
* @Author: xbcao
* @Description: TODO
* @Date: 2023/11/29 18:06:59
* @Since: jdk1.8
* @Version: 1.0
*/
public class VipTickets {
public static void main(String[] args) {
vipRunnable vipRunnable = new vipRunnable();
Thread normal = new Thread(vipRunnable,"普通用户"); //普通用户
Thread vip3 = new Thread(vipRunnable, "vip3会员"); //vip3会员
Thread vip7 = new Thread(vipRunnable, "vip7会员"); //vip7会员
normal.start();
vip3.start();
vip7.start();
}
}
class vipRunnable implements Runnable {
private static int ticketCount = 20;
@SneakyThrows
@Override
public void run() {
while (true) {
if ("normal".equals(Thread.currentThread().getName())) {
Thread.sleep(3000);
}
if ("vip3".equals(Thread.currentThread().getName())) {
Thread.sleep(2000);
}
if ("vip7".equals(Thread.currentThread().getName())) {
Thread.sleep(1000);
}
boolean result = synchronizedMethod();
if (result) {
break;
}
}
}
public static synchronized boolean synchronizedMethod() {
if (ticketCount == 0) {
return true;
} else {
System.out.println(Thread.currentThread().getName() + "正在抢购第" + ticketCount + "张票");
ticketCount--;
return false;
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yolovf/thread.git
git@gitee.com:yolovf/thread.git
yolovf
thread
thread
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385