車站只剩 50 張從武漢到北京的車票,現有 3 個視窗售賣,用程式模擬售票的過程,要求使用同步方法保證售票過程中票數的正確性
public class SellTicketBySync implements Runnable {
private int ticket = 50;//剩餘的票數
//重寫run方法
@Override
public void run() {
while (true) {
if (this.ticket > 0) {
SellTicket();
} else {
break;
}
}
}
public synchronized void SellTicket() {
if (ticket > 0) {
try {
//執行緒休眠50毫秒
Thread.sleep(50);
System.out.println(Thread.currentThread().getName()+"出售第"+ticket--+"張車票");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
//建立一個Runnable範例
SellTicketBySync sellTicketBySync = new SellTicketBySync();
//建立3條執行緒,併為3條執行緒指定名稱
Thread thread01 = new Thread(sellTicketBySync,"視窗1");
Thread thread02 = new Thread(sellTicketBySync,"視窗2");
Thread thread03 = new Thread(sellTicketBySync,"視窗3");
thread01.start();
thread02.start();
thread03.start();
}
}