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

标签 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

我尝试仅在我的主函数中设置 s ,仅在可调用类中设置,现在我在它们两个中设置它只是为了安全起见,但它们都还没有起作用。

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

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

最佳答案

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

关于Java,将值传递给实现 Callable 的类的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17785910/

相关文章:

typescript - 如何仅获取类的构造签名?

java - 如何在正则表达式的帮助下使用 replaceAll() 方法忽略字符串中的特殊字符 ($ ^ + () {} 等)

python - 在线程中更改 QObject 样式表时出错

c++ - 构造函数的最佳形式?传值还是传引用?

linux - 负责配置进程数和线程数的Linux配置参数有哪些?

linux - 当从另一个线程发出信号时,如何在阻塞套接字上从 "disengage"返回 `accept`?

javascript - JavaScript中的函数和构造函数之间有什么区别?

java - 用于不同属性的 DynamoDB Mapper 框架

java - 简单 JOGL 测试用例中的 NullPointerException

java - java读取目录中的文件并存储其在目录中的偏移量