美文网首页多线程基础学习
2019-07-14 多线程模式master-work

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

作者: zecan | 来源:发表于2021-06-28 23:13 被阅读0次

    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() {
        }
    
    

    相关文章

      网友评论

        本文标题:2019-07-14 多线程模式master-work

        本文链接:https://www.haomeiwen.com/subject/ogxwkctx.html