java实现购票系统的多线程安全

package com.zl.byticket;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author 丢了风筝的线
 * @see 测试多线程购电影票
 *
 */
public class ByTicket {
	public static void main(String[] args) {

		List<Integer> cinemaList = new ArrayList<Integer>();
		cinemaList.add(1);
		cinemaList.add(2);
		cinemaList.add(3);
		cinemaList.add(7);
		cinemaList.add(11);
		cinemaList.add(9);
		cinemaList.add(5);
		cinemaList.add(30);

		// 初始化影院
		Cinema cinema = new Cinema(cinemaList, "太平洋影院");
		List<Integer> c1List = new ArrayList<>();
		c1List.add(1);
		c1List.add(11);
		c1List.add(30);

		// 客户
		Thread c1 = new Thread(new Customer(c1List, cinema), "何老板");
		c1.start();

		List<Integer> c2List = new ArrayList<>();
		c2List.add(1);
		c2List.add(30);
		Thread c2 = new Thread(new Customer(c2List, cinema), "王小皮");
		c2.start();

	}
}

package com.zl.byticket;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author 丢了风筝的线
 * @see 模拟电影院的买票功能
 */
public class Cinema {

	// 座位数
	private List<Integer> availableSeats;

	// 影院的名字
	private String name;

	public Cinema(List<Integer> availableSeats, String name) {
		super();
		this.availableSeats = availableSeats;
		this.name = name;
	}

	/**
	 * 
	 * @param seats买的那些座位
	 * @return 购票是否成功
	 */
	public boolean saleTickets(List<Integer> seats) {

		System.out.println("现剩余的座位为:" + availableSeats);

		// 复制一份原来的票集
		List<Integer> copyList = new ArrayList<Integer>();
		copyList.addAll(availableSeats);

		// 现有座位的容器和顾客需要购买的票的容器做减法
		copyList.removeAll(seats);

		// 判断购票是否成功
		if ((availableSeats.size() - copyList.size()) != seats.size()) {
			return false;
		}

		// 购买成功之后,需要更改原票集的数据
		availableSeats = copyList;
		return true;
	}

}

package com.zl.byticket;

import java.util.List;

/**
 * 
 * @author 丢了风筝的线
 * @see 购票的顾客
 */
public class Customer implements Runnable {

	// 要购买的座位
	List<Integer> seats;

	// 从那个影院购买
	Cinema cinema;

	public Customer(List<Integer> seats, Cinema cinema) {
		this.seats = seats;
		this.cinema = cinema;
	}

	@Override
	public void run() {
		synchronized (cinema) {

			boolean flag = cinema.saleTickets(seats);
			if (flag) {
				System.out.println("购票成功  " + Thread.currentThread().getName() + "购买的位置为:" + seats);
			} else {
				System.out.println("购票失败  " + Thread.currentThread().getName() + "购买失败");
			}
		}

	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值