2012-04-29 91 views
0

java中創建線程時出錯。錯誤發生在「MainApp」,RandomCharacterThread是錯誤。線程t1期待一個字符,而我給它一個int值。這是造成錯誤的原因。我已經添加了評論,以使社區的代碼更加清晰。java中創建線程時出錯

//Main class. 
//program to display random numbers and characters using threads. 
public class MainApp 
{ 

    public static void main(String[] args) 
    { 
     new MainApp().start(); 
    } 
    public void start() 
    { 
     Thread t1 = new Thread (new RandomCharacterThread("1")); 
     t1.start(); 

    } 

} 


//RandomCharacterThread. 
//Imports. 
import java.util.Random; 
//===================================================================== 
public class RandomCharacterThread implements Runnable 
{ 
//Variables. 
    char letter; 
    int repeats; 
    Random rand = new Random(); 
//Constructor 
//===================================================================== 
public void RandomCharacterThread(char x) 
{ 
    letter = x; 
    repeats = rand.nextInt(999); 
} 
public void run() 
{ 
    try 
    { 
     for(int i = 0;i < repeats; i++) 
     { 
      System.out.println("Character: " + letter); 
     } 

    } 
    catch(Exception e) 
    { 

    } 
} 

} 
+2

它通常是一個壞主意,以拋棄異常。 –

+0

感謝我記住這一點。 – Pendo826

+0

在這種情況下,您不需要try/catch塊。刪除它,如果發生RuntimeException或Error,它將被打印。 –

回答

3

你的 「構造」 需要char作爲參數;你通過String。你想要做這樣的事情

Thread t1 = new Thread (new RandomCharacterThread('1')); 

注單引號,而不是雙引號,這使它成爲一個char常量,而不是String一個字符。

我說「構造函數」在引號中,因爲你實際上沒有一個:你有一個返回void的方法,其名稱與該類相同。刪除「空白」,你會很好。構造函數沒有返回類型都:

public RandomCharacterThread(char x) 
{ 
    ... 

這是一個很常見的新手的錯誤,但大多數人只讓它一次!

+0

我仍然有錯誤。只有在參數中沒有任何內容時,錯誤纔會消失。也沒有什麼是從線程打印出來的。 – Pendo826

+0

@ConorPendlebury:啊!我看到了另一個問題:請參閱我編輯的答案。 –

+0

工作表示感謝。我正在瀏覽一些最近的工作,我有公共類subClass(String x)。爲什麼你會說我不能在這種情況下使用類? – Pendo826

0

RandomCharacterThread類的構造函數需要類型爲char的參數,因爲在傳遞字符串時會引發錯誤。
這是正確的版本。

Thread t1 = new Thread (new RandomCharacterThread('1'));