package com.itheima.threaddemo;
public class BuyTicket {
public static void main(String[] args) {
Station station = new Station(20);
new Thread(station, "小红").start();
new Thread(station, "小明").start();
new Thread(station, "黄牛").start();
//先打印的主线程票数,说明主线程执行的末尾,其他线程还可以执行
System.out.println("剩余票数"+station.getTicketNums());
}
}
class Station implements Runnable{
//车站里面有票
private int ticketNums;
private boolean flag;
public Station(int ticketNums) {
if(ticketNums > 0) {
flag = true;
}else {
flag = false;
}
this.ticketNums = ticketNums;
}
public void setTicketNums(int ticketNums) {
this.ticketNums = ticketNums;
}
public int getTicketNums() {
return ticketNums;
}
//买票方法
public void buy() {
if(ticketNums <= 0) {
flag = false;
return;
}
System.out.println(Thread.currentThread().getName()+"在买第"+ticketNums--+"票");
}
@Override
public synchronized void run() {//这里的锁就是this,一定要保证锁的唯一
while (flag) {
buy();
}
}
}
多线程买票
最新推荐文章于 2023-04-11 22:43:16 发布