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

时间:2012-03-11 20:17:24

标签: java multithreading loops command-line

我正在尝试创建多个线程,其数量取决于命令行的输入。我知道扩展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);
    }
}
}

4 个答案:

答案 0 :(得分:8)

是的,它正在创建和启动n个帖子,所有帖子都在打印Run:后立即结束。

答案 1 :(得分:6)

您可以选择ExecutorService

示例代码:

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

相关文章:(使用ExecutorService替代普通Thread的优势)

ExecutorService vs Casual Thread Spawner

How to properly use Java Executor?

答案 2 :(得分:2)

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

答案 3 :(得分:0)

@ ravindra-babu建议使用ExecutorService的另一个简单示例

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

然后您要做的就是在循环内创建一个新线程

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