2014-07-09 71 views
-1

我想构建一个应用程序,该应用程序使用多线程执行特定的实用程序。我想控制线程的数量。这是我想要做的:在for循环中执行一定数量的线程

//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中这样做?

+2

你找'ExecutorService'? – TheLostMind

回答

1

您可以使用Java执行人框架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; 

} 

    } 
+0

是的,这就是我想要的。另外我想知道是否有额外的开销,因为当我将池大小设置为5时,与单次迭代相比,该过程要慢得多。 – salvador

+0

请记住,如果您认为帖子回应您的问题标记为完成 – paul