HSeldon HSeldon - 1 month ago 20
Java Question

Java - Creating Multiple Threads with a For Loop

I am trying to create multiple threads, the number of which is dependent on the input from the command line. I know extending Thread isn't the best OO practice unless you are making a specialized version of Thread, but hypothetically is this code creating the desired result?

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);
}
}
}

Answer

Yes, it is creating and starting n threads, all ending immediately after printing Run: and their name.

Comments