java中的執行緒同步問題 模擬出售火車票
阿新 • • 發佈:2019-02-19
/*
功能:模擬火車售票視窗
Thread.currentThread().getName()//獲取到當前執行緒的名稱
1.解決所有執行緒共享 tickets。
解決思路:①將tickets的資料型別改為static。建立了3個視窗, 每一個視窗代表一個執行緒。
② 建立一個主視窗物件,建立三個執行緒物件,分別表示3個執行緒,傳入相同的引數(視窗物件)。
2.解決同一張票被賣出去多次。(程式的併發執行造成的,多個執行緒同時訪問tickets)
解決思路:(保證其原子性)當a執行緒在執行某段程式碼的時候,其他執行緒必須等待a執行完之後才能執行這段程式碼。
在需要同步的程式碼段上加入synchronized (this){}//物件鎖 將要同步的程式碼塊包起來
*/
//售票主視窗
class TicketWindows implements Runnable {
private int tickets = 2000;// 總票數
public void run() {
while (true) {
//if else 要保證其原子行 同步程式碼塊
synchronized (this) {
if (tickets > 0) {
// 顯示售票資訊
System.out.println(Thread.currentThread().getName()
+ "正在售票中 ....還剩" + tickets + "張票");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
tickets--;
} else {
// 退出售票視窗
break;
}
}
// 判斷是否還有票
}
}
}
public class TestTickets {
public static void main(String[] args) {
/*
///建立了3個視窗 每一個視窗代表一個執行緒
TicketWindows tWindows1=new TicketWindows();
TicketWindows tWindows2=new TicketWindows();
TicketWindows tWindows3=new TicketWindows();
Thread thread1=new Thread(tWindows1);
Thread thread2=new Thread(tWindows2);
Thread thread3=newThread(tWindows3);
thread1.start();
thread2.start();
thread3.start();
*/TicketWindows tWindows1 = new TicketWindows();
Thread thread1 = new Thread(tWindows1);
Thread thread2 = new Thread(tWindows1);
Thread thread3 = new Thread(tWindows1);
thread1.start();
thread2.start();
thread3.start();
}
}