我正在尝试创建多个线程,其数量取决于命令行的输入.我知道扩展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); } } }
解决方法
是的,它正在创建和启动n个线程,所有这些线程都在打印后立即结束Run:及其名称.