Java,将值传递给实现Callable的类的构造函数

时间:2013-07-22 11:02:00

标签: java multithreading constructor 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

我尝试仅在我的main函数中设置 s ,仅在可调用类中设置,现在我在两个设置它只是为了安全,但它们都没有工作。< / p>

这个问题的根源是什么?那些可调用的实例是否共享DamgardJurick对象?我缺少什么?

很抱歉这个很长的问题,我找不到办法让它变得更简单。

1 个答案:

答案 0 :(得分:1)

所有线程共享DamgardJurik的相同实例,每个线程将其s设置为从主线程获得的值。为每个线程使用单独的DamgardJurik实例。