1.将一个大任务分解成几个小的任务,并发执行,提高系统的吞吐量。
2.master
//任务队列
protected Queue<Object> workQueue = new ConcurrentLinkedQueue<Object>();
//woker队列
protected Map<String,Thread> threadMap = new HashMap<>();
//子任务的结果处理集
protected Map<String,Object> = new ConcurrentHashMap<>();
//是否所有的子任务都结束了
public boolean isComplete() {
for (Map.Entry<String, Thread> entry : threadMap.entrySet()) {
if (entry.getValue().getState()!=Thread.State.TERMINATED){
return false;
}
}
return true;
}
public Master(Worker worker,int workerCount){
worker.setQueue(workQueue);
worker.setResultMap(resultMap);
//创建worker
for (int i = 0; i < countWorker; i++) {
threadMap.put(Integer.toString(i),new Thread(worker));
}
}
//提交一个任务
public void submit(Object job){
workQuery.add(job);
}
//返回子任务结果集
public Map<String,Object> getResultMap(){
return resultMap;
}
//开始运行所有的worker
public void execute(){
for (Map.Entry<String,Thread> entry : threadMap.entrySet()){
entry.getValue().start();
}
worker implements Runnable
//任务队列,用于取得子任务
protected Queue<Object> workQueue;
//子任务处理结果集
protected Map<String, Object> resultMap;
public void setWorkQueue(Queue<Object> workQueue) {
this.workQueue = workQueue;
}
public void setResultMap(Map<String, Object> resultMap) {
this.resultMap = resultMap;
}
//子任务处理的逻辑,在子类中实现具体逻辑
public Object handle(Object input) {
return input;
}
@Override
public void run() {
}
网友评论