好的,所以我对此感到麻烦,也许我只是想了太久或很笨,但这就是我所拥有的以及我正在尝试做的事情:

所有更新代码均已修复,不再存在运行问题。

public class myClass program {
   int [] w = null;
   int [] x = null;
   Thread T = null;
   public static void main(String [] args){
    x = new int[5];
    w = new int[5];

 // here i am trying to invoke a new thread passing the index
 // of my array, then incrementing the index each time i create a new thread
 // the purpose is to fill each index each time the new thread runs.

    for(int i = 0; i < w.length; i ++){
      // T = new Thread(new myThreadClass(w[i])); // only passes 0 take this out and
      T = new Thread( new myThreadClass(i));      // pass i so the position changes
      T.start();
      try{
        Thread.sleep(100);
        }catch(Exception e){}

   }
}


在我单独的类myThreadClass.java中,我具有以下内容:

public class myThreadClass extends Thread{
 int [] w = null;
 int position = 0;
 int value = 1;

  public myThreadClass(int p){
    this.position = p
    w = myClass.w;
  }

  @Override
  public void run(){
   // synchronize the thread so there is no memory cache problems
   //
   synchronized(w){
      w[position] = value;
   }
  }

}


当我从myClass打印出w的输出时:

我得到w = 1 0 0 0 0

但我要w = 1 1 1 1 1

编辑-我现在得到正确的输出-检查代码以进行更改

最佳答案

在这部分myThreadClass(w[i])中,您没有传递索引,而是传递了一个零值,因为w是一个由5个元素组成的数组,所有元素均初始化为默认值0。

您应该改为myThreadClass(i)

10-08 14:57