我正在尝试并行解决多个优化实例,并创建了一个玩具示例。当我用一个线程解决每个实例时,它可以正常工作。当我开始增加线程数时,某些实例会收到内存不足的异常。我想知道是否有人可以给我提示如何解决此问题。

我尽力使示例尽可能简单。

import java.util.Iterator;
import java.util.Vector;

public class ConcurrentExample {
    public static int fixed;
    public static int nbWarehouses;
    public static int nbStores;
    public static void main(String[] args) throws IloException, InterruptedException {
        int nProblems = 20;

        final Vector<Integer> v = new Vector<Integer>();
        for (int i = 1; i <= nProblems; ++i) v.add(i);

        final Iterator<Integer> it = v.iterator();
        int nTHREADS = 2; //numofCores
        Thread[] threads = new Thread[nTHREADS ];

        for (int t = 0; t < nTHREADS ; ++t) {
              threads[t] = new Thread(new Runnable() {
                public void run() {
                while (true) {
                    int i;
                    synchronized (it) {
                      if ( !it.hasNext() ) return;
                      i = it.next();
                    }
                    fixed = 400 + i;
                    nbWarehouses = 400 ;
                    nbStores     = 800 + i;
                    int[] capacity = new int[nbWarehouses];
                    int[][]  supplyCost= new int[nbStores][nbWarehouses];
                    for(int w=0; w< nbWarehouses ; w++) {
                        capacity[w] = (nbStores/ nbWarehouses) + (w % ( nbStores/ nbWarehouses));
                        for(int s=0; s< nbStores ; s++) {
                            supplyCost[s][w] = 1 + ( ( s + 10 * w) % 100 );
                         }
                    }
                }
               }
            }
          );
        }

        for (int t = 0; t < nTHREADS; ++t) { threads[t].start(); }

        for (int t = 0; t < nTHREADS; ++t) { threads[t].join(); }


    }

}



当我使用两个线程时,收到以下错误:

Exception in thread "Thread-0" java.lang.ArrayIndexOutOfBoundsException: 801
    at concurrent$1.run(concurrent.java:36)
    at java.lang.Thread.run(Thread.java:748)


设置NTHREADS=4时,出现以下错误。

Exception in thread "Thread-1" Exception in thread "Thread-0" Exception in thread "Thread-2" java.lang.ArrayIndexOutOfBoundsException: 802
    at concurrent$1.run(concurrent.java:36)
    at java.lang.Thread.run(Thread.java:748)
java.lang.ArrayIndexOutOfBoundsException: 801
    at concurrent$1.run(concurrent.java:36)
    at java.lang.Thread.run(Thread.java:748)
java.lang.ArrayIndexOutOfBoundsException: 803
    at concurrent$1.run(concurrent.java:36)
    at java.lang.Thread.run(Thread.java:748)


编辑:一件非常重要的事情是,我必须保持全局定义的变量。这只是一个玩具的例子。在实际模型中,我具有静态变量,可以在迭代解决方案方法中通过多种方法访问这些变量。

最佳答案

当两个线程启动时,“ nbStores”可能会增加,通过它在第36行完成的迭代可能会获得ArrayIndexOutOfException。

第一个线程以
int [] [] supplyCost =新的int [nbStores] [nbWarehouses]; // nbStores = 801
一旦第二个线程启动,nbStores将变为802,这可能会影响循环运行,直到s = 801。
for(int s = 0; s

09-27 18:33