首页 > 代码库 > java并发编程之Master-Worker模式

java并发编程之Master-Worker模式

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<String, Thread> threadMap = new HashMap<String, Thread>();
private Map<Object, Object> result = new ConcurrentHashMap<Object, Object>();
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<String, Thread> thread : threadMap.entrySet()) {
thread.getValue().start();
}
}
public Map<Object, Object> getResult() {
return result;
}
public void setResult(Map<Object, Object> result) {
this.result = result;
}
public boolean isComplete() {
for(Map.Entry<String, Thread> 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<Object, Object> 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<Object, Object> getResult() {
return result;
}
public void setQueue(Queue queue) {
this.queue = queue;
}
public void setResult(Map<Object, Object> result) {
this.result = result;
}
}
package cn.fcl.masterworker;
public class PlusWorker extends Worker{
@Override
public Object handle(Object obj) {
Integer value = http://www.mamicode.com/(Integer) obj;>

 

本文出自 “温故而知新” 博客,请务必保留此出处http://fangchunliu.blog.51cto.com/1269779/1410800