Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
}
}
like image 723
HSeldon Avatar asked Mar 11 '12 20:03

HSeldon


People also ask

Can Java run multiple threads?

Multithreading in Java is a process of executing two or more threads simultaneously to maximum utilization of CPU. Multithreaded applications execute two or more threads run concurrently. Hence, it is also known as Concurrency in Java. Each thread runs parallel to each other.

Can you make multiple thread to execute same instructions?

Yes, A program can run two threads at the same time. it is called Multi threading.


3 Answers

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

like image 158
Daniel Hershcovich Avatar answered Oct 11 '22 21:10

Daniel Hershcovich


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?

like image 38
Ravindra babu Avatar answered Oct 11 '22 21:10

Ravindra babu


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();
            }
        }
    }
}
like image 25
Er. Joshi Avatar answered Oct 11 '22 20:10

Er. Joshi