Java 开发 2.0: Kilim 简介
2010-05-21 00:00:00 来源:WEB开发网清单 5. 一个简单的程序
import kilim.Mailbox;
import kilim.Task;
public class CalculationCooperation {
public static void main(String[] args) {
Mailbox<Calculation> sharedMailbox = new Mailbox<Calculation>();
Task deferred = new DeferredDivision(sharedMailbox);
Task calculator = new Calculator(sharedMailbox);
deffered.start();
calculator.start();
}
}
运行这两个角色会得到如清单 6 所示的输出。如果运行此代码,您的输出可能有所不同,但活动的逻辑顺序将保持不变。在清单 6 中,DeferredDivision 请求计算,Calculator 使用一个答案作为响应。
清单 6. 您的输出将有所不同 —— 各个角色不是一成不变的
[java] I need to know the answer of something
[java] Calculator determined answer
[java] Answer is: The answer of 0.36477377 divided by 0.96829189 is 0.37671881
[java] I need to know the answer of something
[java] Calculator determined answer
[java] Answer is: The answer of 0.40326269 divided by 0.38055487 is 1.05967029
[java] I need to know the answer of something
[java] Calculator determined answer
[java] Answer is: The answer of 0.16258913 divided by 0.91854403 is 0.17700744
[java] I need to know the answer of something
[java] Calculator determined answer
[java] Answer is: The answer of 0.77380722 divided by 0.49075363 is 1.57677330
结束语
角色模型支持采用一种更安全的机制来在进程(或角色)之间进行消息传递,极大地方便了并发编程。此模型的实现因语言和框架的不同而不同。我建议参考 Erlang 的角色,其次是 Scala 的角色。两种实现都很简洁,都具有各自的语法。
如果您想要利用 “plain Jane” Java 角色,那么您最好的选择可能是 Kilim 或一种类似框架。世上没有免费的午餐,但基于角色的框架确实使并发编程以及利用多核进程变得更加简单。
更多精彩
赞助商链接