zoukankan      html  css  js  c++  java
  • Groovy 学习手册(7)

    10. Groovy GPars

    GPars 一开始在 Groovy 中作为一个单独的项目,同时带来了很多并发的机制。它包含了很多并行的map/redueActors,以及其他很多并发的模块。

    1. Parallel Map-Reduce

    在下面的例子中,我们定义了一个包含毕业年份和平均分数的Student类。

    class Student {
            int graduationYear; 
            double gpa; 
    }
    

    同时定义个包含Student的 List,这时你就可以使用 GPars 类库对 List 执行并行的 map-reduce 操作。

    GParsPool.withPool {
        // a map-reduce functional style (students is a Collection)
        def bestGpa = students.parallel
            .filter{ s -> s.graduationYear == Student.THIS_YEAR }
            .map{ s -> s.gpa }
            .max()
    }
    

    静态方法GParsPool.withPool 接收一个闭包以及增加集合的方法(使用 Groovy 的 Category 机制)。parallel 实际上从给定的集合中创建了一个ParallelArray对象,在使用时包装了一个包装类。

    Tip
    详情请参考Map-Reduce

    2. Actor

    Actor 设计模式在开发并发软件时非常有用。在此模式中,每一个 Actor 执行自己的线程和操作只属于自己的数据。这些数据不能被其他的线程所操作。消息在 Actor 中被传递,从而改变数据。你也可以创建无状态的 Actor。
    当在某一时间数据只能被一个线程所改变时,我们就称之为是线程安全的。

    import groovyx.gpars.actor.Actor
    import groovyx.gpars.actor.DefaultActor
    
    class Dragon extends DefaultActor {
        int age
        void afterStart() {
            age = new Random().nextInt(1000) + 1
        }
        void act() {
            loop {
                react { int num ->
                   if (num > age)
                     reply 'too old'
                  else if (num < age)
                     reply 'too young'
                  else  {
                    reply 'you guessed right!'
                    terminate()
                  }
                }
            }
        }
    }
    // Guesses the age of the Dragon
    class Guesser extends DefaultActor {
        String name
        Actor server
        int myNum
        void act() {
            loop {
              myNum = new Random().nextInt(1000) + 1
              server.send myNum
              react {
                switch (it) {
                  case 'too old': println "$name: $myNum was too old"; break
                   case 'too young': println "$name: $myNum was too young"; break
                  default: println "$name: I won $myNum"; terminate(); break
                }
              }
            }
          }
    }
    
    def master = new  Dragon().start()
    def player = new Guesser(name: 'Guesser', server: master).start()
    
    //this forces main thread to live until both actors stop
    [master, player]*.join()
    

    在这里,Dragon类一开始随机生成在1到1000的年龄的整数。它对一个给定的数字作出反应,如果数字太大,太小,或相同的年龄。Guesser类不停循环,产生一个随机数并发送到Dragon类(也就是Server)。Guesser类从Dragon类得到反馈程序终止时,则猜出正确的年龄了。

  • 相关阅读:
    PHP 多参数方法的重构
    PHP cURL库函数抓取页面内容
    PHP下载远程文件到指定目录
    PHP生成特定长度的纯字母字符串
    PHP提取奇数或偶数下标元素
    Java中的clone()----深复制,浅复制
    LeetCode题解 343.Integer Break
    MySQL学习笔记(四):存储引擎的选择
    存储过程优缺点
    MySQL学习笔记(三):常用函数
  • 原文地址:https://www.cnblogs.com/IcanFixIt/p/6689873.html
Copyright © 2011-2022 走看看