题目:编写一个类似医院的叫号程序(要求:多个窗口叫号,不重号、不跳号)

2019年3月16日
当开始看到这个题目第一个想到的是多线程,打开Eclipse开始别写的时候感觉无从下手。作为一个开发,再工作当中主要用到的是业务,开发过程是copy或者百度,当遇到这种题目真的感觉很绝望,于是先百度,看了一下人家的代码,发现很多JDK提供的类不知道是什么,于是打开JDKAPI文档。发现百度上写的就是生产者-消费者模式。具体是在BlockingQueue中提到的一个例子。

 1  class Producer implements Runnable {  //创建一个生产者,实现多线程接口
 2    private final BlockingQueue queue;   //定义私有属性阻塞队列
 3    Producer(BlockingQueue q) { queue = q; }//定义带参构造,再实例化一个生产者中就要创建好自己的阻塞对立
 4    public void run() {
 5      try {
 6        while(true) { queue.put(produce()); }   //关键是while中的出发条件需要判断queue对象是否是否已经满了,如果满了再put的话将会异常如果在等待时被中断
 7      } catch (InterruptedException ex) { ... handle ...}
 8    }
 9    Object produce() { ... }     //生产方法,里面方法体是需要生产的对象
10  }
11 
12  class Consumer implements Runnable {   //创建一个使用者,实现多线程接口
13    private final BlockingQueue queue;
14    Consumer(BlockingQueue q) { queue = q; }
15    public void run() {
16      try {
17        while(true) { consume(queue.take()); }// 为了实现排队序列情况,获取并移除此队列的头部,在元素变得可用之前一直等待
18      } catch (InterruptedException ex) { ... handle ...}
19    }
20    void consume(Object x) { ... }
21  }
22 
23  class Setup {
24    void main() {
25      BlockingQueue q = new SomeQueueImplementation();
26      Producer p = new Producer(q);
27      Consumer c1 = new Consumer(q);
28      Consumer c2 = new Consumer(q);
29      new Thread(p).start();
30      new Thread(c1).start();
31      new Thread(c2).start();
32    }
33  }

其中涉及到的类有:Executor、BlockingQueue、LinkedBlockingQueue、TimeUnit。

猜你喜欢

转载自www.cnblogs.com/gnwzj/p/10546819.html