• Java 并发编程实战学习笔记——串行任务转并行任务


    package net.jcip.examples; 
    
    import java.util.Collection; 
    import java.util.List; 
    import java.util.Queue; 
    import java.util.concurrent.ConcurrentLinkedQueue; 
    import java.util.concurrent.Executor; 
    import java.util.concurrent.ExecutorService; 
    import java.util.concurrent.Executors; 
    import java.util.concurrent.TimeUnit; 
    
    /** 
     * TransformingSequential 
     * <p/> 
     * Transforming sequential execution into parallel execution 
     * 
     * @author Brian Goetz and Tim Peierls 
     */ 
    public abstract class TransformingSequential { 
    
        void processSequentially(List<Element> elements) { 
            for (Element e : elements) 
                process(e); 
        } 
    
        void processInParallel(Executor exec, List<Element> elements) { 
            for (final Element e : elements) 
                exec.execute(new Runnable() { 
                    public void run() { 
                        process(e); 
                    } 
                }); 
        } 
    
        public abstract void process(Element e); 
    
    
        public <T> void sequentialRecursive(List<Node<T>> nodes, 
                                            Collection<T> results) { 
            for (Node<T> n : nodes) { 
                results.add(n.compute()); 
                sequentialRecursive(n.getChildren(), results); 
            } 
        } 
    
        public <T> void parallelRecursive(final Executor exec, 
                                          List<Node<T>> nodes, 
                                          final Collection<T> results) { 
            for (final Node<T> n : nodes) { 
                exec.execute(new Runnable() { 
                    public void run() { 
                        results.add(n.compute());  //在这里,仅仅计算是并行任务,他自己的递归还是串行任务 
                    } 
                }); 
                parallelRecursive(exec, n.getChildren(), results); 
            } 
        } 
    
        public <T> Collection<T> getParallelResults(List<Node<T>> nodes) 
                throws InterruptedException { 
            ExecutorService exec = Executors.newCachedThreadPool(); 
            Queue<T> resultQueue = new ConcurrentLinkedQueue<T>(); 
            parallelRecursive(exec, nodes, resultQueue); 
            exec.shutdown(); 
            exec.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); 
            return resultQueue; 
        } 
    
        interface Element { 
        } 
    
        interface Node <T> { 
            T compute(); 
    
            List<Node<T>> getChildren(); 
        } 
    } 
    
    
  • 相关阅读:
    设计模式-1-概要(c#版)
    UML图示说明
    阿里云SLB双机IIS多站点负载均衡部署笔记
    阿里云分布式关系数据库DRDS笔记
    一些小经验
    NOSQL场景梳理
    内核linux-3.4.2支持dm9000
    构建根文件系统
    u-boot-1.1.6移植之dm9000
    移植u-boot-1.1.6(原创)
  • 原文地址:https://www.cnblogs.com/daichangya/p/12959143.html
Copyright © 2020-2023  润新知