Java-Création de plusieurs Threads avec une boucle For


J'essaie de créer plusieurs threads, dont le nombre dépend de l'entrée de la ligne de commande. Je sais que l'extension de Thread n'est pas la meilleure pratique OO à moins que vous ne fassiez une version spécialisée de Thread, mais hypothétiquement ce code crée-t-il le résultat souhaité?

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);
    }
}
}
Author: javac, 2012-03-12

3 answers

Oui, il crée et démarre des threads n, tous se terminant immédiatement après l'impression Run: et leur nom.

 7
Author: Daniel Hershcovich, 2012-03-11 20:27:51

Vous avez une meilleure alternative avec ExecutorService

Exemple de 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();
        }
    }
}

Utilisation:

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

Articles connexes: (Avantages de l'utilisation de ExecutorService en remplacement de plain Thread)

ExecutorService vs Spawner Thread occasionnel

Comment utiliser correctement Java Exécuteur testamentaire?

 5
Author: Ravindra babu, 2017-11-22 18:13:58

Une chose importante java JVM peut créer 20000 threads à la fois . Création de 255 threads en 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();
            }
        }
    }
}
 2
Author: Er. Joshi, 2017-11-22 16:25:48