代码拉取完成,页面将自动刷新
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;
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。