模拟售票,学习多线程

假设有火车票100张,创建10个线程模拟10个售票点,每个售票点随机生成时间卖一张票。 打印出售票过程,注意使用synchronized确保同一张票只能卖出一次。

import java.text.SimpleDateFormat;
import java.util.Date;

public class Resource {

	int ticketNum;
	boolean flag = false;
	SimpleDateFormat sdf;

	int i = 1;

	public Resource(int ticketNum) {
		this.ticketNum = ticketNum;

		sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
	}

	public synchronized void sellTicket(Seller s) {
		if (i <= ticketNum) {
			System.out.println("在" + sdf.format(new Date()) + " 第" + s.num
					+ "售票点卖了第" + i + "张票...");
			i++;

		} else {
			flag = true;
		}
	}

}

public class Seller implements Runnable {

	int num;
	Resource rs;

	public Seller(int num, Resource rs) {
		super();
		this.num = num;
		this.rs = rs;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (rs.flag == false) {
			// 调用资源类的同步方法
			rs.sellTicket(this);
			try {
				// 生成随机数(范围1-1000)
				int random = (int) (Math.random() * 1000);
				Thread.sleep(random);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Resource rs = new Resource(100);
		for (int i = 0; i < 10; i++) {
			Thread t = new Thread(new Seller(i, rs));
			t.start();
		}
	}

}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值