2010-11-23 21 views
3

使用線程池在多個線程中運行靜態方法的最佳方式是什麼? 另外我試圖將一個參數傳遞給靜態方法。像從java中的線程池運行靜態方法

Class A{ 
public static runTask(int i){ 
    .... 
} 

} 

,並從主:

ThreadPool pool = new ThreadPool(5, "poolname"); 

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

    A.runTask(i) // but on a new thread... 

} 

謝謝!

+0

我希望你不打算使用可變靜態字段。 – 2010-11-23 11:15:49

回答

1

看看java.util.concurrent.Executors的文檔。它應該滿足您的需求。下面是使用它的一個簡單的例子:

public class ExecutorServiceTest { 
    static ExecutorService threadPool = Executors.newCachedThreadPool(); 

    public static void main(String[] args) throws Exception { 
     // Queue 10 executions of someTask into the threadPool 
     for(int i = 0; i < 10; i++) { 
      runSomeTaskInThreadPool(); 
     } 
     // the shutdown method causes the executor to: 
     // 1. stop accepting new tasks, and 
     // 2. allow previously queued jobs to complete, and 
     // 3. shut down all pooled threads once all jobs are complete 
     threadPool.shutdown(); 
     // block until the threadPool has finished shutting down, 
     // which indicates that all tasks have finished executing 
     threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); 
    } 

    private static void runSomeTaskInThreadPool() { 
     Future future = threadPool.submit(new Runnable() { 
      public void run() { 
       someTask(); 
      } 
     }); 
     // TODO: Maybe keep track of futures to monitor success/failure of task 
    } 

    static AtomicInteger counter = new AtomicInteger(); 
    public static void someTask() { 
     System.out.println("someTask: " + counter.incrementAndGet() 
       + " on thread: " + Thread.currentThread()); 
    } 
} 
+0

你能更具體嗎?哪一位執行者,以及應該如何使用? – yken 2010-11-23 09:40:31