我对多线程和使用设计模式都是新手。
我有一些线程使用显式多线程,如果任何线程都没有计算过某个数字的阶乘,那么每个线程都应该计算它。我为此使用享元模式。
private final long Comp;
private static Map<String, Fact> instances=new HashMap<String, Fact>();
private Fact(long comp) {
Comp=comp;
}
public static Fact getInstance(int num){
String key=String.valueOf(num);
if(!instances.containsKey(key)){
int comp=//calculate factorial of num
instances.put(key, new Fact(comp));
}
return instances.get(key);
}
public long get_Comp(){
return this.Comp;
}
}
public class Th implements Runnable {
// code elited
@Override
public void run() {
//get number and check if it's already in the HashMap, if no,
compute
}
}
如果我这样做,那么说我的线程 Th 是计算阶乘是否正确?
如果我在 Fact (Flyweight) 类中添加计算,那么它是否仍然是 Flyweight,我想是的。
任何其他做我想做的事情的方式也将受到高度赞赏。