Java語言多執行緒實現一個火車站賣票系統

許昌彭于晏的部落格發表於2020-11-24

要實現買票系統,一定要用到多執行緒,因為火車站售票處不可能只有一個賣票口。那麼如何防止兩個口或多個口同時賣出一張票就是一個必須解決的問題。這裡我們可以用到synchrnized同步程式碼塊也就是鎖,來解決這個問題。

synchrnized:同步,可以修飾程式碼塊和方法,修飾的程式碼塊或方法一旦被某個執行緒訪問,則直接鎖住,其他執行緒將無法訪問,只能等著,簡言之:就是一把鎖

synchrnized(鎖物件)
{
程式碼塊
}

注意: 鎖物件需要對所有執行緒共享

同步: 安全性高 效率低
非同步:效率高 安全性低
也可以給方法前加synchrnized修飾符,把整個方法都變成同步方法。

下面是實現售票系統的程式碼:

package maipiao;

public class tickets {
@Override
public String toString() {
return “[”+start + “->” + end + “, price=” + price + “]”;
}
public String getStart() {
return start;
}
public void setStart(String start) {
this.start = start;
}
public String getEnd() {
return end;
}
public void setEnd(String end) {
this.end = end;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
private String start;
private String end;
private int price;
public tickets(String start, String end, int price) {
super();
this.start = start;
this.end = end;
this.price = price;
}
public tickets() {}

}

package maipiao;

import java.util.ArrayList;

public class xitong {

public xitong() {}
private ArrayList<tickets> list = new ArrayList<>();
private String[] start = {"哈爾濱","廣東","湖南","安徽","北京"};
private String[] end = {"深圳","澳門","臺灣","香港"};
public void addliebiao()
{
for(int i=0;i<100;i++) {
	int r1 = (int) (Math.random()*start.length);
	int r2 = (int)(Math.random()*end.length);
	int price = (r1*r2)+100;
	list.add(new tickets(start[r1],end[r2],price));
}
}

public tickets getTickets() {
return list.size() == 0 ? null : list.remove(0);
}
}

package maipiao;
public class chuangkou implements Runnable {
public void run() {
try {
method();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

private synchronized void method() throws InterruptedException {
	Thread.sleep(100);
	xitong xt = new xitong();
	xt.addliebiao();
		while(true){
			tickets ticket = xt.getTickets();
			if(ticket==null) {
				System.out.println("抱歉"+Thread.currentThread().getName()+"票已經售完");
				break;
			}else {
				System.out.println("從"+Thread.currentThread().getName()+"賣出"+ticket+"的票");
			}
		}
}

}

相關文章