码迷,mamicode.com
首页 > 编程语言 > 详细

java并发编程之Master-Worker模式

时间:2014-05-14 18:26:04      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:java

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 = (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);
}
}

 

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

java并发编程之Master-Worker模式,布布扣,bubuko.com

java并发编程之Master-Worker模式

标签:java

原文地址:http://fangchunliu.blog.51cto.com/1269779/1410800

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!