我想學習Java中的多線程概念。我在執行我的代碼片段時遇到了錯誤。Java多線程代碼錯誤
我的代碼片段:
class ThreadDemo {
public static void main(String args[]) {
try{
int [] arr = new int[10] ;
for(int i = 0 ; i < 10 ; i++)
arr[i] = i ;
for(int c =0 ; c < 2 ; c++){
for(int i = 0 ; i < 3 ; i++) //I want to run it on one thread
System.out.println(arr[i]);
for(int j = 0 ; j < 5 ; j++) //I want to run it on another thread
System.out.println(arr[j]);
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
現在,爲了解決這個我已經試過了,
class ThreadDemo {
public static void main(String args[]) {
try{
int [] arr = new int[10] ;
for(int i = 0 ; i < 10 ; i++)
arr[i] = i ;
for(int c =0 ; c < 2 ; c++){
Thread thread1 = new Thread() {
public void run() {
for(int i = 0 ; i < 3 ; i++) //I want to run it on one thread
System.out.println(arr[i]);}
};
Thread thread2 = new Thread() {
public void run() {
for(int j = 0 ; j < 5 ; j++) //I want to run it on one thread
System.out.println(arr[j]);}
};
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
但給人錯誤。任何人都可以幫我解決這個問題嗎?
無論如何,在兩個線程中使用共享數組是不可能的?其實,我有很多共享變量。如果我讓他們最終,我不能修改它們。順便說一句,我沒有給他們打電話,因爲它給出了「做出決定」的錯誤。 – Arpssss 2012-07-30 00:15:03
'方法的局部變量'必須聲明爲'final'才能被匿名內部類訪問。 '類的領域'不一定是最終的,所以也許這將是解決方案。你也可以創建線程不作爲匿名內部類,但作爲單獨的類或只是內部類(不在方法中聲明)並將局部變量傳遞給它們,例如在構造函數中。 – Pshemo 2012-07-30 00:26:18
@Arpssss檢查我編輯的答案。也許你會發現一些有用的:) – Pshemo 2012-07-30 00:43:07