public class Test {
public static void main(String[] args) {
SaleTickets saleTickets = new SaleTickets();
Thread thread1 = new Thread(saleTickets); //创建第一个线程
Thread thread2 = new Thread(saleTickets); //创建第二个线程
thread1.start(); //启动线程
thread2.start();
}
}
//实现线程接口
class SaleTickets implements Runnable {
private int tickets = 50;
public void run() {
while (true) {
synchronized (this) { //同步函数,共享同一个tickets
if (tickets > 0) {
try {
Thread.sleep(100); //使当前线程进入休眠状态
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "售出\t还剩" + (tickets--) + "张票");
}
}
}
}
}
多线程之多人售票
最新推荐文章于 2024-04-16 10:42:36 发布