这段时间在看Java并发编程方面的东西,注意到“生产者-消费者”模式,去某公司笔试的时候也遇到了这样的题,今天顺便把他用程序的方式写了下来。
UML就免了,不想画!顺便吐槽一下,小组开发,一定得用UML吗?随便画点图不行么?)
先上ServiceManager,它相当于大厅里的排号机,客户自己去排号,然后柜台的服务人员会去自动的取号:
- /**
- *
- */
- package com.fcm.thread.banksample;
- import java.util.concurrent.BlockingQueue;
- import java.util.concurrent.PriorityBlockingQueue;
- /**
- * @author fenggcai
- *
- */
- public class ServiceManager {
- /**
- * @param args
- */
- public static void main(String[] args) {
- //only 50 customers could be served a time
- final BlockingQueue<FIFOEntry<Customer>> customerQueue = new PriorityBlockingQueue<FIFOEntry<Customer>>(
- 50);
- for (int i = 0; i < 52; i++) {
- int randomLevel = new Double(Math.random() * 5).intValue();
- Customer c = new Customer("Customer" + i,
- CustomerLevel.values()[randomLevel]);
- new Thread(new CustomerService(customerQueue, c)).start();
- }
- for (int i = 0; i < 5; i++) {
- BankService bs = new BankService(customerQueue);
- new Thread(bs).start();
- try {
- Thread.currentThread().sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }