23

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);
    }
}
}
javac
  • 2,431
  • 4
  • 17
  • 26
HSeldon
  • 419
  • 1
  • 4
  • 9
  • 2
    You said, "extending Thread isn't the best OO practice unless you are making a specialized version of Thread." However, your example does make a specialized version of Thread; looks fine to me. – jyoungdev Nov 12 '12 at 14:27
  • 1
    if you want the check ,you can run your program in debug mode and see how many threads are creeated.. – Rockin Jan 12 '13 at 08:04
  • You re thread is very good. that's is best practice 'n' limit loop. – Aruna D Mahagamage Jul 28 '21 at 16:25

4 Answers4

15

You have better alternative with ExecutorService

Sample code:

import java.util.concurrent.*;

public class ExecutorTest{
    public static void main(String args[]){

        int numberOfTasks = Integer.parseInt(args[0]);
        ExecutorService executor= Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
        try{
            for ( int i=0; i < numberOfTasks; i++){
                executor.execute(new MyRunnable(i));                
            }
        }catch(Exception err){
            err.printStackTrace();
        }
        executor.shutdown(); // once you are done with ExecutorService
    }   
}
class MyRunnable implements Runnable{
    int id;
    public MyRunnable(int i){
        this.id = i;
    }
    public void run(){
        try{
            System.out.println("Runnable started id:"+id);
            System.out.println("Run: "+ Thread.currentThread().getName()); 
            System.out.println("Runnable ended id:"+id);
        }catch(Exception err){
            err.printStackTrace();
        }
    }
}

Usage:

java ExecutorTest 2

Runnable started id:0
Run: pool-1-thread-1
Runnable ended id:0
Runnable started id:1
Run: pool-1-thread-2
Runnable ended id:1

Related posts: ( Advantages of using ExecutorService as a replacement for plain Thread)

ExecutorService vs Casual Thread Spawner

How to properly use Java Executor?

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
  • can you please explain this statement : ExecutorService executor= Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); – Asha Mar 06 '20 at 12:29
  • Thread pool size is equal to number of cpu cores on the machine. If you have 4 core CPU machine, thread pool size is 4. – Ravindra babu Mar 06 '20 at 13:59
11

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

Daniel Hershcovich
  • 3,751
  • 2
  • 30
  • 35
5

One important thing java JVM can create 20000 thread at a time . Creating 255 threads in java

class MyThread1 extends Thread {
    int k;
    public MyThread1(int i) {
            k = i;
    }

    @Override
    public void run() {
        //Your Code
        System.out.println("Thread no. "+k);

    }
}
class MainClass {

    public static void main(String arg[]) throws UnknownHostException {
        Refresh() ;
    }

    public static void Refresh(){

        //create 255 Thread using for loop
        for (int x = 0; x < 256; x++) {
            // Create Thread class 
            MyThread1 temp = new MyThread1(x);
                temp.start();
            try {
                temp.join(10);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
Lonergan6275
  • 1,938
  • 6
  • 32
  • 63
Er. Joshi
  • 185
  • 1
  • 8
-2

Another simple example using ExecutorService as recommended by @ravindra-babu

class MyRunnable implements Runnable{
    int id;
    public MyRunnable(int i){
        this.id = i;
    }
    public void run(){
        try{
            long init = System.currentTimeMillis();
            System.out.println("Start of Thread ID = " + id);
            Thread.sleep(id * 1000);
            long end = System.currentTimeMillis();
            long elapsedTime = end - init;
            System.out.println("Elapsed time of Thread ID " + id + ": " + elapsedTime);
        } catch(Exception err){
            err.printStackTrace();
        }
    }
}

Then all you need to do is create a new Thread inside the loop

public static void main(String[] args) {        
    
    for (int i = 0; i < 10; i++) {
        try{
            ExecutorService executor= Executors.newFixedThreadPool(1);
            executor.execute(new MyRunnable(i));
            executor.shutdown();
        } catch(Exception err){
            err.printStackTrace();
            return;
        }
    }
}
Renan Ribeiro
  • 69
  • 1
  • 8
  • 1
    You shouldn't instantiate a brand new executor service on every iteration of the for loop – Matt Jan 14 '23 at 03:37