Java -使用For循环创建多个线程

时间:2023-01-21 21:02:06

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?

我正在尝试创建多个线程,这些线程的数量取决于来自命令行的输入。我知道扩展线程并不是最好的OO实践,除非您正在创建一个特定版本的线程,但是假设这段代码正在创建期望的结果吗?

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

3 个解决方案

#1


6  

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

是的,它正在创建和启动n个线程,所有线程都在打印运行后立即结束:以及它们的名称。

#2


4  

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替代普通线程的优势)

ExecutorService vs Casual Thread Spawner

ExecutorService vs .临时线程生成者。

How to properly use Java Executor?

如何正确使用Java执行器?

#3


1  

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

java JVM一次可以创建20000个线程,这一点很重要。在java中创建255个线程

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

#1


6  

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

是的,它正在创建和启动n个线程,所有线程都在打印运行后立即结束:以及它们的名称。

#2


4  

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替代普通线程的优势)

ExecutorService vs Casual Thread Spawner

ExecutorService vs .临时线程生成者。

How to properly use Java Executor?

如何正确使用Java执行器?

#3


1  

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

java JVM一次可以创建20000个线程,这一点很重要。在java中创建255个线程

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