[英]Java, Passing value to a constructor of class inplementing Callable
因此,我實現了以下簡單類以並行化獨立的加密過程:
public class SelectionEncryptor implements Callable<BigInteger> {
private DamgardJurik dj;
private byte c;
private int s;
public SelectionEncryptor(DamgardJurik dj, byte c, int s) {
this.dj = dj;
this.c = c;
this.s = s;
}
@Override
public BigInteger call() throws Exception {
dj.setS(s);
BigInteger r = dj.encryption(BigInteger.valueOf(c));
System.out.println("dj s: " + dj.s + ", given s: " + s + ", c: " + c);
return r;
}
}
s只是我們使用的密碼系統的一個參數,但它是確定加密深度的重要參數。
我初始化並運行線程,如下所示:
int s = s_max;
ExecutorService executor = Executors.newFixedThreadPool(selectionBits.length);
ArrayList<Future<BigInteger>> list = new ArrayList<Future<BigInteger>>();
// selectionBits is just a byte array holding 1's and 0's
for (int i = 0; i < selectionBits.length; i++) {
dj.setS(s);
SelectionEncryptor se = new SelectionEncryptor(dj, selectionBits[i], s);
System.out.println("submitted: " + selectionBits[i] + " with s " + s + ", dj s: " + dj.s);
Future<BigInteger> result = executor.submit(se);
list.add(result);
s--;
}
// collecting results
for (Future<BigInteger> future : list) {
try {
BigInteger f = future.get();
out.println(f);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
executor.shutdown();
問題是,即使我將正確的s值發送到SelectionEncryptor,它也將為其使用不同的值。 這是我的程序的示例輸出:
submitted: 1 with s 6, dj s: 6
submitted: 0 with s 5, dj s: 6
submitted: 1 with s 4, dj s: 5
submitted: 0 with s 3, dj s: 3
submitted: 1 with s 2, dj s: 2
submitted: 0 with s 1, dj s: 1
dj s: 4, given s: 1, c: 0
dj s: 2, given s: 2, c: 1
dj s: 2, given s: 3, c: 0
dj s: 2, given s: 4, c: 1
dj s: 2, given s: 6, c: 1
dj s: 2, given s: 5, c: 0
我已經嘗試僅在主函數中,僅在可調用類中設置s ,現在為了安全起見在兩個函數中都設置了s ,但它們都沒有起作用。
這個問題的根源是什么? 這些可調用實例是否共享DamgardJurick對象? 我想念的是什么?
抱歉,這個問題很長,我找不到簡化它的方法。
您的所有線程共享相同的DamgardJurik
實例,每個線程將其s
設置為從主線程獲得的值。 為每個線程使用一個單獨的DamgardJurik
實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.