使用java多线程实现火车站售票的问题,有需要的朋友可以看看。
package com.softeem.demo;
/**
*@author leno
*售票类
*/
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();
}
}