簡體   English   中英

Java相同類的多個實例共享相同的運行對象,但是它們不應該

[英]Java multiple instances of same class share the same running objects, but they shoud not

我正在做一個多線程Java優化算法,出於節省時間的原因,該算法將初始化同一子類的各種實例。 該子類本身具有其他子類。

算法通過隨機運動在搜索空間中搜索最佳解決方案。 因此,如果我運行它的多個實例,則應該利用我系統的核心,並在整個搜索空間內改善搜索范圍。

我注意到,第一個實例運行良好,但是其他實例似乎共享第一個實例的運行對象,即使它們已經完成,也會選擇它們持有的信息。

那不是我想要的; 我希望任何一個實例都為其他實例絕緣。

我正在使用執行器服務:

碼:

ExecutorService executorService = Executors.newCachedThreadPool();
ExecutorCompletionService<float[][]> service = new ExecutorCompletionService<float[][]>(executorService);

IteratedGreedy[] ig = new IteratedGreedy[instances];
Future<float[][]>[] future = new Future[instances];

// launching instances:
for (int i=0; i<instances; i++)
    {       
    path = "\\" + i + ".txt";
    ig[i] = new IteratedGreedy(path);
    future[i] = service.submit(ig[i]);
    }

// retrieveing solutions:
for (int i=1; i<instances; i++)
    {
    solutions[i] = future[i].get();
        }

您可能會想到,IteratedGreedy函數在內部具有自己的子目錄。

任何幫助表示贊賞。

問題是,在代碼中的某個地方,存在一個帶有全局靜態變量的類:

static float[][] matrix;

然后,一種方法使用它:

SomeMethod()
    {
    int f = matrix[i][b];
    }

解決方案是更改方法獲取對象的方式:

float[][] matrix;

SomeMethod(float[][] matrix)
    {
    int f = matrix[i][j];
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM