package com.softeem.demo;
/**
*@authorleno
*售票类
*/
class SaleTicket implements Runnable {
int tickets = 100;
public void run() {
while (tickets > 0) {
sale();
//或者下面这样实现
// synchronized (this) {
// if (tickets > 0) {
// System.out.println(Thread.currentThread().getName() + "卖第"
// + (100 - tickets + 1) + "张票");
// tickets--;
// }
// }
}
}
public synchronized void sale() {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + "卖第"
+ (100 - tickets + 1) + "张票"); //打印第几个线程正在执行
tickets--;
}
}
}
public class TestSaleTicket {
public static void main(String[] args) {
SaleTicket st = new SaleTicket();
new Thread(st, "一号窗口").start();
new Thread(st, "二号窗口").start();
new Thread(st, "三号窗口").start();
new Thread(st, "四号窗口").start();
}
}
用JAVA的多线程实现火车站售票问题
最新推荐文章于 2022-10-19 14:50:23 发布