java併發編程之Master-Worker模式

Master-Worker模式適合在一個任務能夠拆分紅多個小任務來進行的狀況下使用。java

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 = (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<Object, Object> result = master.getResult();
int re = 0;
while(result.size() > 0 || !master.isComplete()) {
Set<Object> 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);
}
}
相關文章
相關標籤/搜索