Java线程中的共享变量

时间:2018-10-31 03:00:55

标签: java multithreading

我的方法运行中需要3个参数。其中两个需要成为共享矩阵的一部分(其中2行),最后一个是master的for索引。如何将那些传递给我的方法运行? 我有一个巨大的矩阵,所以在不同位置复制变量不是最好的主意... 我应该使用这些属性创建另一个类,并使该类实现Runnable吗?

控件 ArrayList旨在用作查看我正在工作的列是否仍与上面行中的列不同的地方,因为它不会生成正确答案。

如何使它们保持在由线程决定的最大数量,而不使我的主线程停止?据我所知,加入线程会使我的mainThread停止。

我的代码如下:

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 个答案:

没有答案
相关问题