Master-Worker模式适合在一个任务可以拆分成多个小任务来进行的情况下使用。

package cn.fcl.masterworker;import java.util.HashMap;import java.util.Map;import java.util.Queue;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ConcurrentLinkedQueue;public class Master {private Queue queue = new ConcurrentLinkedQueue();private Map
threadMap = new HashMap
();private Map
result = new ConcurrentHashMap
();public Master(Worker worker, int count) {worker.setQueue(queue);worker.setResult(result);for(int i = 0; i < count; i++) {threadMap.put(String.valueOf(i), new Thread(worker));}}public void submit(Object obj) {queue.add(obj);}public void execute() {for(Map.Entry
thread : threadMap.entrySet()) {thread.getValue().start();}}public Map
getResult() {return result;}public void setResult(Map
result) {this.result = result;}public boolean isComplete() {for(Map.Entry
thread : threadMap.entrySet()) {if(thread.getValue().getState() != Thread.State.TERMINATED) {return false;}}return true;}}package cn.fcl.masterworker;import java.util.Map;import java.util.Queue;public abstract class Worker implements Runnable {private Queue queue;private Map
result;public void run() {while(true) {Object obj = queue.poll();if(obj == null) {break;}result.put(obj, handle(obj));}}public abstract Object handle(Object obj);public Queue getQueue() {return queue;}public Map
getResult() {return result;}public void setQueue(Queue queue) {this.queue = queue;}public void setResult(Map
result) {this.result = result;}}package cn.fcl.masterworker;public class PlusWorker extends Worker{@Overridepublic Object handle(Object obj) {Integer value = (Integer) obj;return value * value * value;}}package cn.fcl.masterworker;import java.util.Iterator;import java.util.Map;import java.util.Set;public class main {public static void main(String[] args) {Master master = new Master(new PlusWorker(), 5);for(int i = 0; i < 100; i++) {master.submit(i);}master.execute();Map
result = master.getResult();int re = 0;while(result.size() > 0 || !master.isComplete()) {Set
sets = result.keySet();Object key = null;for(Object o : sets) {key = o;break;}if(key == null) {continue;}re += Integer.parseInt(result.get(key).toString());result.remove(key);}System.out.println(re);}}