码迷,mamicode.com
首页 > 编程语言 > 详细

多线程——newFixedThreadPool线程池

时间:2018-10-27 17:43:34      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:center   call   i++   name   exception   public   接口   nis   实现   

newFixedThreadPool线程池:

理解:
  1.固定线程数的线程池。
  2.通过Executors中的静态方法创建:
      public static ExecutorService newFixedThreadPool(int nThreads)或者
      public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory)两种方式。
  3.返回的是ExecutorService对象线程池,例如:ExecutorService executorService = Executors.newFixedThreadPool(10)。
例子:
/**
 * 线程池,实现Runnable接口
 * @author Administrator
 *
 */
public class ThreadPoolRunnable implements Runnable{
    public void run(){
        System.out.println(Thread.currentThread().getName()+"线程");
    }
}
/**
 * 实现Callable线程池
 * @author Administrator
 *
 */
public class ThreadPoolCallable implements Callable<String>{
    @Override
    public String call() throws Exception {
        System.out.println(Thread.currentThread().getName()+"开始执行Callable接口.......");
        return "线程执行完毕!";
    }
}

 

//线程池测试类
public class TestThreadPoolRunnable {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        threadRunnable(5, 10);
        threadCallable(3, 10);
    }

    /**
     * 实现Runnable接口线程池
     * 
     * @param a
     *            创建线程数量
     * @param b
     *            线程池总数
     * @throws InterruptedException
     * @throws ExecutionException
     */
    public static void threadRunnable(int a, int b) throws InterruptedException, ExecutionException {
        // 创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(b);
        for (int i = 0; i < a; i++) {
            // 从线程池中调用线程
            executorService.submit(new ThreadPoolRunnable());
        }
    }

    /**
     * 实现Callable线程池
     * 
     * @param a
     *            创建线程数
     * @param b
     *            线程池总数
     * @throws InterruptedException
     * @throws ExecutionException
     */
    public static void threadCallable(int a, int b) throws InterruptedException, ExecutionException {
        ExecutorService executorService = Executors.newFixedThreadPool(b);
        for (int i = 0; i < a; i++) {
            Future<String> s = executorService.submit(new ThreadPoolCallable());
            System.out.println(s.get());
        }
    }
}
结果:
pool-1-thread-1线程
pool-1-thread-3线程
pool-1-thread-2线程
pool-1-thread-5线程
pool-1-thread-4线程
pool-2-thread-1开始执行Callable接口.......
线程执行完毕!
pool-2-thread-2开始执行Callable接口.......
线程执行完毕!
pool-2-thread-3开始执行Callable接口.......
线程执行完毕!

 

 

多线程——newFixedThreadPool线程池

标签:center   call   i++   name   exception   public   接口   nis   实现   

原文地址:https://www.cnblogs.com/whx20100101/p/9862369.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!