派号系统----多线程学习

直接贴代码:觉得非常实用!
package lab_11;

import java.util.LinkedList;

public class NumStore {
LinkedList<Integer> list = new LinkedList<Integer>();
Integer i = 1;
public synchronized Integer push(){
list.add(++i);
//必须在获得锁的情况下才能调用notifyAll和wait方法
this.notifyAll();
return i;
}

public synchronized Integer pop(){
while(list.isEmpty()){
try {
//
wait();//在这里阻塞了

} catch (InterruptedException e) {
e.printStackTrace();
}
}
return list.remove(0);
}
}
package lab_11;

public class QuHao extends Thread{
private NumStore ns ;
private String name;

public QuHao(String name,NumStore ns){
this.name = name;
this.ns = ns;
}
public void run(){
while(true){
System.out.println("您的号码是:"+ns.push()+",请排队等候叫号。。");
try {
Thread.sleep((int)(Math.random()*1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package lab_11;

//派叫号系统
public class PaiJiaoHaoSystem {

/**
* @param args
*/
public static void main(String[] args) {
NumStore ns = new NumStore();

QuHao q1 = new QuHao("取号机1",ns);
QuHao q2 = new QuHao("取号机2",ns);

Window w1 = new Window("窗口1",ns);
Window w2 = new Window("窗口2",ns);
Window w3 = new Window("窗口3",ns);

q1.start();
q2.start();
w1.start();
w2.start();
w3.start();

}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值