当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。