Java中線程部分知識(shí)中,售票程序非常經(jīng)典。程序中也有一些問題存在!
需求:模擬3個(gè)窗口同時(shí)在售100張票。
問題1:為什么100張票被賣出了300張票?
原因:因?yàn)閠ickets是非靜態(tài)的,非靜態(tài)的成員變量數(shù)據(jù)是在每個(gè)對(duì)象中都會(huì)維護(hù)一份數(shù)據(jù)的,三個(gè)線程對(duì)象就會(huì)有三份。
解決方案:把tickets票數(shù)共享出來給三個(gè)線程對(duì)象使用。使用static修飾。
問題2: 出現(xiàn)了線程安全問題 ?
線程安全問題的解決方案:sun提供了線程同步機(jī)制讓我們解決這類問題的。
java線程同步機(jī)制的方式:
方式一:同步代碼塊
方式二:同步函數(shù)
class SellTickets extends Thread{ static int tickets=1;//票數(shù) 這里 必須定義為static。不然 非靜態(tài)的成員變量,非靜態(tài)的成員變量數(shù)據(jù)是在每個(gè)對(duì)象中都會(huì)維護(hù)一份數(shù)據(jù)的。三個(gè)線程對(duì)象就會(huì)有三份。 public SellTickets(String threadName) { super(threadName); } public void run() { while(true){ synchronized ("鎖") { if(tickets==101){//或者 if(tickets>100){ System.out.println("票已經(jīng)賣完啦-_-..."); break; } System.out.println(Thread.currentThread().getName()+"賣了第"+tickets+"號(hào)票"); tickets++; /* if(tickets==101){ //錯(cuò)誤的。當(dāng)ticket==101時(shí),只跳出一個(gè)線程。其它兩個(gè)線程還存在tickets++。 break; } /* if(Thread.currentThread().getName().equals("窗口2")){ //窗口2最多只能賣一張票,就結(jié)束了 break; } */ } //System.out.println(Thread.currentThread().getName()+"鎖后..."); } } } public class Demo4 { public static void main(String[] args) { //創(chuàng)建三個(gè)線程對(duì)象,模擬三個(gè)窗口 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方法..."); } }
新聞熱點(diǎn)
疑難解答
圖片精選