首页
学习
活动
专区
圈层
工具
发布

JUC基础:购票案例

购票问题

public class Thread01 {

public static void main(String[] args) {

Ticket01 ticket = new Ticket01();

new Thread(()->ticket.sale(), "A").start();

new Thread(()->ticket.sale(), "B").start();

}

}

class Ticket01 {

int number = 1;

public void sale() {

if (number > 0) {

if (Thread.currentThread().getName().equals("A")) {

try {

TimeUnit.SECONDS.sleep(3);

} catch (InterruptedException e) {

throw new RuntimeException(e);

}

}

}

}

}

购票解决

public class Thread02 {

public static void main(String[] args) {

Ticket02 ticket = new Ticket02();

new Thread(()->ticket.sale(), "A").start();

new Thread(()->ticket.sale(), "B").start();

}

}

class Ticket02 {

int number = 1;

public synchronized void sale() {

if (number > 0) {

if (Thread.currentThread().getName().equals("A")) {

try {

TimeUnit.SECONDS.sleep(3);

} catch (InterruptedException e) {

throw new RuntimeException(e);

}

}

}

}

}

  • 发表于:
  • 原文链接https://page.om.qq.com/page/OEl8K4Me-AcPbsRwNJd8ciOQ0
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。
领券