建立售卖线程类:
public class TicketRunnable implements Runnable {
private int ticketCount = 10;//模拟火车票数量
public void run() {
while (true) {
synchronized (this) {//线程加锁
try {
if (ticketCount>0) {
ticketCount--;
Thread.sleep(100);
System.out.println(Thread.currentThread().getName() + "卖了1张票,还剩票数为 " + ticketCount);
}
else {
return;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
线程测试类:
public class Sales {
public static void main(String[] args) {
TicketRunnable r1 = new TicketRunnable();
Thread t1 = new Thread(r1,"1号窗口");
Thread t2 = new Thread(r1,"2号窗口");
Thread t3 = new Thread(r1,"3号窗口");
t1.start();
t2.start();
t3.start();
}
}
执行结果:
1号窗口卖了1张票,还剩票数为 9
1号窗口卖了1张票,还剩票数为 8
1号窗口卖了1张票,还剩票数为 7
1号窗口卖了1张票,还剩票数为 6
2号窗口卖了1张票,还剩票数为 5
2号窗口卖了1张票,还剩票数为 4
2号窗口卖了1张票,还剩票数为 3
3号窗口卖了1张票,还剩票数为 2
3号窗口卖了1张票,还剩票数为 1
3号窗口卖了1张票,还剩票数为 0