2014-07-09 70 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