10. Groovy GPars
GPars 一开始在 Groovy 中作为一个单独的项目,同时带来了很多并发的机制。它包含了很多并行的map/redue
,Actors
,以及其他很多并发的模块。
1. Parallel Map-Reduce
在下面的例子中,我们定义了一个包含毕业年份和平均分数的Student
类。
复制代码
1
2
3
4class Student { int graduationYear; double gpa; }
同时定义个包含Student
的 List,这时你就可以使用 GPars 类库对 List 执行并行的 map-reduce 操作。
复制代码
1
2
3
4
5
6
7GParsPool.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。
当在某一时间数据只能被一个线程所改变时,我们就称之为是线程安全的。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48import 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
类得到反馈程序终止时,则猜出正确的年龄了。
最后
以上就是清爽耳机最近收集整理的关于Groovy 学习手册(7)的全部内容,更多相关Groovy内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复