在for循环中执行一定量的线程

时间:2014-07-09 12:07:52

标签: java multithreading

我想构建一个使用多线程执行某个实用程序的应用程序。我想控制线程数量。这就是我想要做的事情:

    //initialize the number of threads to be 10
for(int i = 0; i < BIG_VALUE; i++) {
    RunnableObject rb = new RunnableObject(i);
    rb.run();
    //the for loop should run for 10 loops. When one of the threads finish its job
    //the for loop continues and runs another thread. The amount of threads should 
    //always be 10
}

我怎么能用Java做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以尝试使用Java Executor框架http://docs.oracle.com/javase/tutorial/essential/concurrency/executors.html

这是一个如何使用

的例子
    public class SimpleThreadPool {



public static void main(String[] args) {

    ExecutorService executor = Executors.newFixedThreadPool(5);

    for (int i = 0; i < 10; i++) {

        Runnable worker = new WorkerThread('' + i);

        executor.execute(worker);

      }

    executor.shutdown();

    while (!executor.isTerminated()) {

    }

    System.out.println('Finished all threads');

}



 }






         public class WorkerThread implements Runnable {



private String command;

public WorkerThread(String s){

    this.command=s;

}



@Override
public void run() {

    System.out.println(Thread.currentThread().getName()+' Start. Command = '+command);

    processCommand();

    System.out.println(Thread.currentThread().getName()+' End.');

}



private void processCommand() {

    try {

        Thread.sleep(5000);

    } catch (InterruptedException e) {

        e.printStackTrace();

    }

}



@Override
public String toString(){

    return this.command;

}

  }