2012-07-29 80 views
0

我想學習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()); 
    } 
    } 
} 

但給人錯誤。任何人都可以幫我解決這個問題嗎?

回答

2

for (int c = 0; c < 2; c++) { 
    Thread thread1 = new Thread() {//<- here 

要創建繼承Thread類的匿名內部類。你必須知道,匿名內部類,他們創建的,因此,如果你想訪問int [] arr你必須讓最終像

final int[] arr = new int[10]; 

而且你創建的線程,但你沒有啓動它們的方法have access only to final local variables。要做到這一點,請調用他們的start()方法,如thread1.start()


如果你不想申報方法的局部變量作爲最終你應該考慮創建線程不是匿名內部類,但作爲單獨的類例如

class MyThread extends Thread { 
    int[] array; 
    int iterations; 

    public MyThread(int[] arr, int i) { 
     array=arr; 
     iterations = i; 
    } 

    @Override 
    public void run() { 
     for (int i = 0; i < iterations; i++) 
      System.out.println(array[i]); 
    } 
} 

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++) { 
       MyThread thread1 = new MyThread(arr, 3); 
       MyThread thread2 = new MyThread(arr, 5); 
       thread1.start(); 
       thread2.start(); 
      } 

     } catch (Exception e) { 
      System.err.println("Error: " + e.getMessage()); 
     } 
    } 
} 
+0

無論如何,在兩個線程中使用共享數組是不可能的?其實,我有很多共享變量。如果我讓他們最終,我不能修改它們。順便說一句,我沒有給他們打電話,因爲它給出了「做出決定」的錯誤。 – Arpssss 2012-07-30 00:15:03

+0

'方法的局部變量'必須聲明爲'final'才能被匿名內部類訪問。 '類的領域'不一定是最終的,所以也許這將是解決方案。你也可以創建線程不作爲匿名內部類,但作爲單獨的類或只是內部類(不在方法中聲明)並將局部變量傳遞給它們,例如在構造函數中。 – Pshemo 2012-07-30 00:26:18

+0

@Arpssss檢查我編輯的答案。也許你會發現一些有用的:) – Pshemo 2012-07-30 00:43:07

0

FYI:擴展線程不如果你實際上沒有提供任何額外的邏輯,這是最好的想法。最好使用Runnable並將其傳遞給線程構造函數。

Thread t = new Thread(new Runnable() { 
    public void run() { 
    } 
}); 
t.start(); 

除此之外,正如其他人指出的,任何直接在匿名類中的變量都需要聲明爲final。