package com.cal;
public class TicketsThread {
public static void main(String[] args) {
T tt=new T();
Thread thread=new Thread(tt,"窗口1");
Thread thread2=new Thread(tt,"窗口2");
Thread thread3=new Thread(tt,"窗口3");
thread.start();
thread2.start();
thread3.start();
}
}
class T implements Runnable{
//总的票数
private int count=5;
@Override
public void run() {
synchronized (this) {
while(count>0){
count--;
System.out.println(Thread.currentThread().getName()+"卖了一张票,还剩下"+count+"张票");
}
}
}
}
该博客展示了用Java模拟火车站售票的代码。通过创建线程类实现Runnable接口,设置总票数,利用synchronized关键字保证线程安全,模拟多个窗口同时售票,每个窗口卖出票后更新剩余票数并输出信息。

5723

被折叠的 条评论
为什么被折叠?



