2019-07-14 多线程模式master-work

1.将一个大任务分解成几个小的任务,并发执行,提高系统的吞吐量。

2.master

//任务队列
protected Queue workQueue = new ConcurrentLinkedQueue();
//woker队列
protected Map threadMap = new HashMap<>();
//子任务的结果处理集
protected Map = new ConcurrentHashMap<>(); 

//是否所有的子任务都结束了
    public boolean isComplete() {
        for (Map.Entry 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 getResultMap(){
        return resultMap;
    }

//开始运行所有的worker
public void  execute(){
        for (Map.Entry entry : threadMap.entrySet()){
            entry.getValue().start();
        }
 
 

worker implements Runnable

//任务队列,用于取得子任务
    protected Queue workQueue;
    //子任务处理结果集
    protected Map resultMap;
public void setWorkQueue(Queue workQueue) {
        this.workQueue = workQueue;
    }

    public void setResultMap(Map resultMap) {
        this.resultMap = resultMap;
    }

  //子任务处理的逻辑,在子类中实现具体逻辑
    public Object handle(Object input) {
        return input;
    }
 @Override
    public void run() {
    }

 

                            
                        
                    
                    
                    

你可能感兴趣的:(2019-07-14 多线程模式master-work)