创建线程时java中的错误。错误出现在“MainApp”中,而 RandomCharacterThread 是错误。线程 t1 期待一个 char 而我给它一个 int 值。这就是导致错误的原因。我添加了注释以使社区的代码更清晰。
//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)
{
}
}
}