2012-04-29 88 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'));