Java中線程部分知識中,售票程序非常經典。程序中也有一些問題存在!
需求:模擬3個窗口同時在售100張票。
問題1:為什么100張票被賣出了300張票?
原因:因為tickets是非靜態的,非靜態的成員變量數據是在每個對象中都會維護一份數據的,三個線程對象就會有三份。
解決方案:把tickets票數共享出來給三個線程對象使用。使用static修飾。
問題2: 出現了線程安全問題 ?
線程安全問題的解決方案:sun提供了線程同步機制讓我們解決這類問題的。
java線程同步機制的方式:
方式一:同步代碼塊
方式二:同步函數
class SellTickets extends Thread{
static int tickets=1;//票數 這里 必須定義為static。不然 非靜態的成員變量,非靜態的成員變量數據是在每個對象中都會維護一份數據的。三個線程對象就會有三份。
public SellTickets(String threadName) {
super(threadName);
}
public void run() {
while(true){
synchronized ("鎖") {
if(tickets==101){//或者 if(tickets>100){
System.out.println("票已經賣完啦-_-...");
break;
}
System.out.println(Thread.currentThread().getName()+"賣了第"+tickets+"號票");
tickets++;
/*
if(tickets==101){ //錯誤的。當ticket==101時,只跳出一個線程。其它兩個線程還存在tickets++。
break;
}
/*
if(Thread.currentThread().getName().equals("窗口2")){ //窗口2最多只能賣一張票,就結束了
break;
}
*/
}
//System.out.println(Thread.currentThread().getName()+"鎖后...");
}
}
}
public class Demo4 {
public static void main(String[] args) {
//創建三個線程對象,模擬三個窗口
SellTickets s1=new SellTickets("窗口1");
SellTickets s2=new SellTickets("窗口2");
SellTickets s3=new SellTickets("窗口3");
//開啟線程售票
s1.start();
s2.start();
s3.start();
System.out.println("main方法...");
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。