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

2022-09-02 01:32:55

我正在尝试创建多个线程,其数量取决于命令行的输入。我知道扩展Thread不是最好的OO实践,除非你正在制作一个专门的Thread版本,但假设这段代码是否创造了所需的结果?

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

答案 1

是的,它正在创建和启动线程,所有线程在打印及其名称后立即结束。nRun:


答案 2

你有更好的替代方案与执行器服务

示例代码:

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

用法:

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

相关文章: ( 用作普通版替代品的优势ExecutorServiceThread)

ExecutorService vs Casual Thread Spawner

如何正确使用Java Executor?


推荐