當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Executors newFixedThreadPool()用法及代碼示例


Executors 類的 newFixedThreadPool() 方法創建一個線程池,該線程池重用固定數量的線程,這些線程在共享的無界隊列上運行。在任何時候,最多有 n 個線程是活動的處理任務。如果在所有線程都處於活動狀態時提交了其他任務,它們將在隊列中等待,直到有線程可用。

用法

public static ExecutorService newFixedThreadPool(int nThreads)
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory)

參數

nThreads - 池中的線程數

threadFactory - 創建新線程時使用的工廠

返回

拋出

IllegalArgumentException

NullPointerException

例子1

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ExecutornewFixedThreadPoolExample1   {
    
   public static void main(final String[] arguments) throws InterruptedException {
      ThreadFactory ThreadFactory = Executors.defaultThreadFactory();
      ExecutorService excr = Executors.newFixedThreadPool(5 , ThreadFactory);
      ThreadPoolExecutor mypool = (ThreadPoolExecutor) excr;
      System.out.println("size of mypool:" + mypool.getPoolSize());
      excr.submit(new Threadimpl());
      excr.shutdown();
   }  

static class Threadimpl implements Runnable {
      public void run() {
         try {
            Long num = (long) (Math.random() * 30);
            System.out.println("Thread Name:" +Thread.currentThread().getName());
               TimeUnit.SECONDS.sleep(num);
            System.out.println("after sleep Thread Name:" +Thread.currentThread().getName());
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
   }

}

輸出:

size of mypool:0
Thread Name:pool-1-thread-1
after sleep Thread Name:pool-1-thread-1

例子2

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ExecutornewFixedThreadPoolExample2   {
    
   public static void main(final String[] arguments) throws InterruptedException {
      ExecutorService excr = Executors.newFixedThreadPool(5);
      ThreadPoolExecutor mypool = (ThreadPoolExecutor) excr;
      System.out.println("size of mypool:" + mypool.getPoolSize());
      excr.submit(new Threadimpl());
      excr.shutdown();
   }  

static class Threadimpl implements Runnable {
      public void run() {
         try {
            Long num = (long) (Math.random() * 30);
            System.out.println("Thread Name:" +Thread.currentThread().getName());
               TimeUnit.SECONDS.sleep(num);
            System.out.println("after sleep Thread Name:" +Thread.currentThread().getName());
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
   }

}

輸出:

size of mypool:0
Thread Name:pool-1-thread-1
after sleep Thread Name:pool-1-thread-1




相關用法


注:本文由純淨天空篩選整理自 Java Executors newFixedThreadPool() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。