好吧,所以我遇到了這個問題,也許我只是想太長時間或者很笨,但這裏是我所擁有的以及我想要做的事情:在main中創建數組並填充來自單獨線程的數據
更新代碼全部固定不再有運行問題。
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
EDITED-我現在獲得正確的輸出 - 檢查更改
謝謝你。結果我所要做的就是't = new Thread(new myThreadClass(i))'我知道這非常簡單。再次感謝 –
+1的真正問題丹。 :-) – Gray