多线程 电影票 java_【JAVA基础】- 多线程电影票售票案例

本文介绍了三种Java实现多线程售卖电影票的方式:1) 继承Thread类并使用synchronized同步代码块;2) 实现Runnable接口并使用synchronized同步代码块;3) 实现Runnable接口并利用Lock锁(ReentrantLock)确保线程安全。通过这三个实例,详细展示了如何在并发环境下避免票数售卖异常。
摘要由CSDN通过智能技术生成

三种实现方式

继承Thread类,synchronized同步代码块

public class SellTicket extends Thread {

// 多个对象共享,必须static修饰

private static int tickets = 100;

@Override

public void run() {

while (true) {

synchronized (SellTicket.class) {

try {

sleep(1000);

} catch (Exception e) {

e.printStackTrace();

}

if (tickets > 0) {

System.out.println(getName() + " 正在出售第 " + tickets-- + " 张票");

}

}

}

}

}

public class TicketDemo {

public static void main(String[] args){

SellTicket thread01 = new SellTicket();

SellTicket thread02 = new SellTicket();

SellTicket thread03 = new SellTicket();

thread01.setName("窗口一");

thread02.setName("窗口二");

thread03.setName("窗口三");

thread01.start();

thread02.start();

thread03.start();

}

}

实现runnable接口,同步代码块

public class SellTicket2 implements Runnable {

// 多个对象共享,必须static修饰

private static int tickets = 100;

@Override

public void run() {

while (true) {

synchronized (SellTicket2.class) {

if (tickets > 0) {

try {

Thread.sleep(1000);

} catch (Exception e) {

e.printStackTrace();

}

System.out.println(Thread.currentThread().getName() + " 正在出售第 " + tickets-- + " 张票");

}

}

}

}

}

public class TicketDemo2 {

public static void main(String[] args) {

SellTicket2 sellTicket2 = new SellTicket2();

Thread thread01 = new Thread(sellTicket2);

Thread thread02 = new Thread(sellTicket2);

Thread thread03 = new Thread(sellTicket2);

thread01.setName("窗口一");

thread02.setName("窗口二");

thread03.setName("窗口三");

thread01.start();

thread02.start();

thread03.start();

}

}

实现runable接口,Lock锁实现线程安全

public class SellTicket3 implements Runnable {

// 多个对象共享,必须static修饰

private static int tickets = 100;

private Lock lock = new ReentrantLock();

@Override

public void run() {

while (true) {

lock.lock();

if (tickets > 0) {

try {

Thread.sleep(1000);

} catch (Exception e) {

e.printStackTrace();

}

System.out.println(Thread.currentThread().getName() + " 正在出售第 " + tickets-- + " 张票");

}

lock.unlock();

}

}

}

public class TicketDemo3 {

public static void main(String[] args) {

SellTicket3 sellTicket3 = new SellTicket3();

Thread thread01 = new Thread(sellTicket3);

Thread thread02 = new Thread(sellTicket3);

Thread thread03 = new Thread(sellTicket3);

thread01.setName("窗口一");

thread02.setName("窗口二");

thread03.setName("窗口三");

thread01.start();

thread02.start();

thread03.start();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值