Java 开发 2.0: Kilim 简介
2010-05-21 00:00:00 来源:WEB开发网DeferredDivision
DeferredDivision 类中使用了特定于 Kilim 的类。该类执行多项操作,但总体来讲它的工作非常简单:使用随机数(类型为 BigDecimal)创建 Calculation 的实例,将它们发送到 Calculator 角色。而且,该类还会检查共享的 MailBox,以查看其中是否有任何 Calculation。如果检索到的一个 Calculation 实例有一个答案,DeferredDivision 将打印它。
清单 2. DeferredDivision 创建随机除数和被除数
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Date;
import java.util.Random;
import kilim.Mailbox;
import kilim.Pausable;
import kilim.Task;
public class DeferredDivision extends Task {
private Mailbox<Calculation> mailbox;
public DeferredDivision(Mailbox<Calculation> mailbox) {
super();
this.mailbox = mailbox;
}
@Override
public void execute() throws Pausable, Exception {
Random numberGenerator = new Random(new Date().getTime());
MathContext context = new MathContext(8);
while (true) {
System.out.println("I need to know the answer of something");
mailbox.putnb(new Calculation(
new BigDecimal(numberGenerator.nextDouble(), context),
new BigDecimal(numberGenerator.nextDouble(), context)));
Task.sleep(1000);
Calculation answer = mailbox.getnb(); // no block
if (answer != null && answer.getAnswer() != null) {
System.out.println("Answer is: " + answer.printAnswer());
}
}
}
}
更多精彩
赞助商链接