Java - 使用 For 循环创建多个线程
2022-09-02 01:32:55
我正在尝试创建多个线程,其数量取决于命令行的输入。我知道扩展Thread不是最好的OO实践,除非你正在制作一个专门的Thread版本,但假设这段代码是否创造了所需的结果?
class MyThread extends Thread {
public MyThread (String s) {
super(s);
}
public void run() {
System.out.println("Run: "+ getName());
}
}
class TestThread {
public static void main (String arg[]) {
Scanner input = new Scanner(System.in);
System.out.println("Please input the number of Threads you want to create: ");
int n = input.nextInt();
System.out.println("You selected " + n + " Threads");
for (int x=0; x<n; x++)
{
MyThread temp= new MyThread("Thread #" + x);
temp.start();
System.out.println("Started Thread:" + x);
}
}
}