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();
}
}
}
}
多线程售卖门票
最新推荐文章于 2022-07-20 11:18:55 发布