派号系统----多线程学习 多线程thread
程序员文章站
2024-02-05 16:16:22
...
直接贴代码:觉得非常实用!
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();
}
}
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();
}
}
上一篇: 上了J道 J#OOJava编程读书
下一篇: 千裏共良宵 音乐生活情感游戏