併發編程10 - 線程池

實現線程池

  • Executors創建線程池
ExecutorService executorService = Executors.newFixedThreadPool(4);
  • ThreadPoolExecutor構造方法
// Java線程池的完整構造函數
public ThreadPoolExecutor(
  int corePoolSize, // 線程池長期維持的線程數,即使線程處於Idle狀態,也不會回收。
  int maximumPoolSize, // 線程數的上限
  long keepAliveTime, TimeUnit unit, // 超過corePoolSize的線程的idle時長,
                                     // 超過這個時間,多餘的線程會被回收。
  BlockingQueue<Runnable> workQueue, // 任務的排隊隊列
  ThreadFactory threadFactory, // 新線程的產生方式
  RejectedExecutionHandler handler) // 拒絕策略

執行線程的任務

Future<T> submit(Callable<T> task)	
void execute(Runnable command)	
Future<?> submit(Runnable task)	

demo

  • 構造線程池
int poolSize = Runtime.getRuntime().availableProcessors() * 2;
BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(512);
RejectedExecutionHandler policy = new ThreadPoolExecutor.DiscardPolicy();
executorService = new ThreadPoolExecutor(poolSize, poolSize,
    0, TimeUnit.SECONDS,
            queue,
            policy);
  • 獲取單個結果
Future.get() //能夠阻塞等待執行結果
get(long timeout, TimeUnit unit) //可以指定等待的超時時間。
  • 獲取多個結果
void solve(Executor executor, Collection<Callable<Result>> solvers)
   throws InterruptedException, ExecutionException {
   
   CompletionService<Result> ecs = new ExecutorCompletionService<Result>(executor);// 構造器
   
   for (Callable<Result> s : solvers)// 提交所有任務
       ecs.submit(s);
       
   int n = solvers.size();
   for (int i = 0; i < n; ++i) {// 獲取每一個完成的任務
       Result r = ecs.take().get();
       if (r != null)
           use(r);
   }
}
  • 單個任務的超時時間
//方法可以指定等待的超時時間,超時未完成會拋出TimeoutException。
V Future.get(long timeout, TimeUnit unit)
  • 多個任務的超時時間
public void testLatch(ExecutorService executorService, List<Runnable> tasks) 
    throws InterruptedException{
      
    CountDownLatch latch = new CountDownLatch(tasks.size());
      for(Runnable r : tasks){
          executorService.submit(new Runnable() {
              @Override
              public void run() {
                  try{
                      r.run();
                  }finally {
                      latch.countDown();// countDown
                  }
              }
          });
      }
      latch.await(10, TimeUnit.SECONDS); // 指定超時時間
  }

參考文檔

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章