Java语言多线程实现一个火车站卖票系统

要实现买票系统,一定要用到多线程,因为火车站售票处不可能只有一个卖票口。那么如何防止两个口或多个口同时卖出一张票就是一个必须解决的问题。这里我们可以用到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+"的票");
			}
		}
}

}

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页