package com.multith.java;
public class Ticket implements Runnable{
private int num=100;
@Override
public void run() {
while(true) {
synchronized (this) { //同步代碼塊
if(num>0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
num--;
System.out.println(Thread.currentThread().getName()+
" 賣出一張票,還剩:"+ num + "張");
}else {
System.out.println(Thread.currentThread().getName()+" 票已售完!");
break;
}
}
}
}
public static void main(String[] args) {
Ticket tic = new Ticket();
Thread t1 = new Thread(tic,"窗口A");
Thread t2 = new Thread(tic,"窗口B");
Thread t3 = new Thread(tic,"窗口C");
t1.start();
t2.start();
t3.start();
}
}
設計三個線程,實現動物園售票窗口進行賣票,每天總共最多隻能出售100張票,售完後所有窗口都停止售票
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.