有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java线程中的多线程共享变量

我的方法运行需要3个参数。其中两个需要是共享矩阵(其中两行)的一部分,最后一个是主索引。我如何将这些传递给我的方法运行? 我有一个很大的矩阵,所以在不同的地方复制变量可能不是最好的主意。。。 我应该用这些atributes创建另一个类,并使这个类实现可运行吗

控件ArrayList用于查看我正在处理的列是否仍然与上一行中的列不同,因为它无法生成正确的答案

如何使它们保持在线程决定的最大值,而不使主线程停止?据我所知,加入一个线程会使我的主线程停止

我的代码如下所示:

public class MochilaCeroUno extends Thread {
    protected List<Item> itemList = new ArrayList<Item>();
    protected int maxWeight = 0;
    protected int solutionWeight = 0;
    protected int profit = 0;
    protected boolean calculated = false;
    static int threads;
    static List<MyPair> control;

运行方法:

public void run(List<Integer> filaAnterior, List<Integer> filaActual, int i) {

        MyPair pair = new MyPair(i, 0);
        control.set((i - 1) % threads, pair);
        int numFilaAnterior = i - 1;

        if (numFilaAnterior >= 0) {
            for (int j = 0; j <= maxWeight; j++) {  //Posar concurrencia aqui
                if (control.get((numFilaAnterior - 1) % threads).getCol() > j) {
                    if (j > 0) {
                        int wH = itemList.get(i - 1).getWeight();
                        if (wH > j) {
                            filaActual.add(filaAnterior.get(j));
                        } else {
                            filaActual.add(Math.max(filaAnterior.get(j), itemList.get(i - 1).getValue() + filaAnterior.get(j - wH)));
                        }
                    } else {
                        filaActual.add(0);
                    }
                } else {
                    j--;
                    yield();
                }
            }
            super.run();
        }
    }

调用运行并必须创建线程的方法:

public List<Item> calcSolution() {
    int n = itemList.size();

    setInitialStateForCalculation();
    if (n > 0 && maxWeight > 0) {
        List<List<Integer>> c = new ArrayList<List<Integer>>();
        List<Integer> curr = new ArrayList<Integer>();


        c.add(curr);
        for (int j = 0; j <= maxWeight; j++) {
            curr.add(0);
        }

        for (int i = 1; i <= n; i++) {
            List<Integer> prev = curr;
            c.add(curr = new ArrayList<Integer>());
            new MochilaCeroUno().start();
           ...

共 (0) 个答案