多线程售卖门票

public  static  void main(String[] args){
	MyRunnable runnable=new MyRunnable();
	Thread t1 =new Thread(runable);   t1.setNmae("海淀区");
	Thread t2=new Thread(runnable);t2.setName("朝阳区");
	Thread t3=new Thread(runnable);t3.setName("丰台区");
	Thread t4=new Thread(runnable);t4.setName("延庆区");
	Thread t5=new Thread(runnable);t5.setName("东城区");
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		t5.start();

}
//如果实现数据空间资源共享,建议创建线程使用实现runnable接口的方式
class MyRunnable implements Runnable{
//票源数据100张
public void run(){
	try{
		sell();
	}catch(Exception e){
		e.printStackTrace();
	}
}
//wait()         线程等待,他会释放数据空间
//notify()       线程唤醒,换线等待线程中的第一个线程
//notifyAll()    线程唤醒,同时唤醒所有等待线程
public void sell(){
//同步代码块,代码锁,方发锁,对象锁
	synachrinized(this){
		while(ticket<100){
			this.notifyAll();//唤醒等待序列的其他线程
			System.out.println(Thread.currentThread().getName()+"卖了第"+ticket+"张票");
			ticket++;
			try{
				this.wait();//线程等待 ,释放空间
			}catch(Exception e){
				e.	printStackTrace();
			}
		}
	}
}			
					

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值