①.master负责手机客户端的请求,将任务分发给work,回收work处理结果,
②.work做具体的业务逻辑,并将结果通知到master
这里做了一个给每个员工涨薪30%,并计算需要支付的薪资
具体实现:
master:
private LinkedBlockingQueuequeue = new LinkedBlockingQueue (); private ConcurrentHashMap resultMap = new ConcurrentHashMap (); private HashMap workeMap = new HashMap (); public Master(Work work, Integer workerCount) { if (workerCount <= 0) return; work.setQueue(queue); work.setResultMap(resultMap); for (int i = 0; i < workerCount; i++) { workeMap.put(i, new Thread(work, "T" + (i + 1))); } } public void putWorker(Money m) throws Exception { if (m == null) return; queue.add(m); } /** * 启动所有工作进程 */ public void startWorker() { for (Map.Entry entry : workeMap.entrySet()) { if(entry.getValue().getState() == Thread.State.NEW){ entry.getValue().start(); } } } /** * 每人工资涨薪30%,计算应付总额 * * @return */ public double sum() { double sum = 0; for (Map.Entry entry : resultMap.entrySet()) { sum += entry.getValue().getMoney(); } return sum; } /** * 所有工作线程是否都完毕 * * @return */ public boolean isCompleted() { for (Map.Entry entry : workeMap.entrySet()) { if (entry.getValue().getState() != Thread.State.TERMINATED) return false; } return true; } work(可根据需要自行扩展):
private LinkedBlockingQueuequeue = new LinkedBlockingQueue (); private ConcurrentHashMap resultMap = new ConcurrentHashMap (); @Override public void run() { try { while (true) { Thread.sleep(3000); Money money = this.queue.poll(); if (money == null) break; double nowMoney = money.getMoney() + (money.getMoney() * 0.3); System.out.println("工号:" + money.getId() + ",原工资:" + money.getMoney() + ",现工资:" + nowMoney + ",当前工作work:" + Thread.currentThread().getName()); money.setMoney(nowMoney); resultMap.put(money.getId(), money); } } catch (InterruptedException e) { e.printStackTrace(); } } 测试:
Master m = new Master(new Work(),5); m.putWorker(new Money("E1234567891", 2000.00)); m.putWorker(new Money("E1234567892", 1500.00)); m.putWorker(new Money("E1234567893", 6000.00)); m.putWorker(new Money("E1234567894", 4500.00)); m.putWorker(new Money("E1234567895", 2200.00)); m.putWorker(new Money("E1234567896", 3000.00)); m.putWorker(new Money("E1234567897", 5000.00)); m.putWorker(new Money("E1234567898", 7000.00)); m.putWorker(new Money("E1234567899", 6500.00)); m.putWorker(new Money("E1234567810", 2200.00)); m.startWorker(); long startTime = System.currentTimeMillis(); while (true) { if (m.isCompleted()) { System.out.println("结算总金额:" + m.sum() + "耗时:" + (System.currentTimeMillis() - startTime) + " ms"); break; } }控制台日志:
工号:E1234567893,原工资:6000.0,现工资:7800.0,当前工作work:T4工号:E1234567894,原工资:4500.0,现工资:5850.0,当前工作work:T1工号:E1234567891,原工资:2000.0,现工资:2600.0,当前工作work:T2工号:E1234567892,原工资:1500.0,现工资:1950.0,当前工作work:T5工号:E1234567895,原工资:2200.0,现工资:2860.0,当前工作work:T3工号:E1234567896,原工资:3000.0,现工资:3900.0,当前工作work:T2工号:E1234567899,原工资:6500.0,现工资:8450.0,当前工作work:T1工号:E1234567810,原工资:2200.0,现工资:2860.0,当前工作work:T5工号:E1234567898,原工资:7000.0,现工资:9100.0,当前工作work:T3工号:E1234567897,原工资:5000.0,现工资:6500.0,当前工作work:T4结算总金额:51870.0耗时:9001 ms