美文网首页
线程池的使用

线程池的使用

作者: 王二牛同学 | 来源:发表于2018-08-18 18:15 被阅读0次

文章源代码地址:https://github.com/Grrui/executor

1. 使用线程池原因

简单说就是因为线程的创建、销毁也是一个开销很大的活动。后来出现了线程池的概念,大家发现:呀,我们可以使用线程池,通过线程池的重用,就不必繁琐的创建、销毁线程了。然后大家就开始疯狂的使用线程池了。

2. 四种线程池对象介绍

本文主要介绍四种线程池对象:

  1. FixedThreadPool
  2. SingleThreadPool
  3. CachedThreadPool
  4. ScheduledThreadPool

2.1. FixedThreadPool

public static ExecutorService newFixedThreadPool(int nThreads)

解释

  1. 线程池最大线程数为nThreads
  2. 当任务数超过nThreads时,会使用一个无界队列存储提交的任务。
  3. 创建线程池时,若无任务,则线程池中不会创建任何线程。

使用:

import java.util.concurrent.*;

public class FixedThreadPool {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 6; i++) {
            FutureTask futureTask = new FutureTask(new MyThread());
            // 提交任务
            executorService.submit(futureTask);
        }
        // 关闭线程池
        executorService.shutdown();
    }
}

class MyThread implements Callable {

    @Override
    public Object call() throws Exception {
        System.out.println("Thread: " + Thread.currentThread().getName() + " begin...");
        Thread.sleep(5 * 1000);
        System.out.println("Thread: " + Thread.currentThread().getName() + " end...");
        return null;
    }
}

控制台输出

Thread: pool-1-thread-1 begin...
Thread: pool-1-thread-3 begin...
Thread: pool-1-thread-2 begin...
Thread: pool-1-thread-1 end...
Thread: pool-1-thread-2 end...
Thread: pool-1-thread-3 end...
Thread: pool-1-thread-2 begin...
Thread: pool-1-thread-3 begin...
Thread: pool-1-thread-1 begin...
Thread: pool-1-thread-2 end...
Thread: pool-1-thread-3 end...
Thread: pool-1-thread-1 end...

逻辑比较简单,创建一个最大3个线程的线程池,执行6个任务。控制台输出可以看出,最多三个线程同时执行;复用这三个线程完成6个任务。

2.2. SingleThreadPool

public static ExecutorService newSingleThreadExecutor()

解释

  1. 线程池只有一个线程。
  2. 当任务数超过一个时,会使用一个无界队列存储提交的任务。

使用:

import java.util.concurrent.*;

public class SingleThreadPool {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 3; i++) {
            FutureTask futureTask = new FutureTask(new MySingleThread());
            // 提交任务
            executorService.submit(futureTask);
        }
        // 关闭线程池
        executorService.shutdown();
    }
}

class MySingleThread implements Callable {

    @Override
    public Object call() throws Exception {
        System.out.println("Thread: " + Thread.currentThread().getName() + " begin...");
        Thread.sleep(5 * 1000);
        System.out.println("Thread: " + Thread.currentThread().getName() + " end...");
        return null;
    }
}

控制台输出

Thread: pool-1-thread-1 begin...
Thread: pool-1-thread-1 end...
Thread: pool-1-thread-1 begin...
Thread: pool-1-thread-1 end...
Thread: pool-1-thread-1 begin...
Thread: pool-1-thread-1 end...

解释
输出可以看出,只有一个线程pool-1-thread-1循环复用完成了所有任务。

2.3. CachedThreadPool

public static ExecutorService newCachedThreadPool()

解释

  1. 线程池最大线程数为Integer.MAX_VALUE。
  2. 当某个线程空闲60s,则会自动销毁。

使用:

package com.example.demo.executor;

import java.util.concurrent.*;

public class CachedThreadPool {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 3; i++) {
            FutureTask futureTask = new FutureTask(new MyCachedThread());
            // 提交任务
            executorService.submit(futureTask);
        }
        // 关闭线程池
        executorService.shutdown();
    }
}

class MyCachedThread implements Callable {

    @Override
    public Object call() throws Exception {
        System.out.println("Thread: " + Thread.currentThread().getName() + " begin...");
        Thread.sleep(5 * 1000);
        System.out.println("Thread: " + Thread.currentThread().getName() + " end...");
        return null;
    }
}

控制台输出

Thread: pool-1-thread-1 begin...
Thread: pool-1-thread-3 begin...
Thread: pool-1-thread-2 begin...
Thread: pool-1-thread-1 end...
Thread: pool-1-thread-2 end...
Thread: pool-1-thread-3 end...

解释
每产生一个任务,立即分配线程执行。当某个线程空闲60s时,会自动销毁。

2.4. ScheduledThreadPool

public static ExecutorService newScheduledThreadPool()

解释

  1. 线程池最大线程数为Integer.MAX_VALUE。
  2. 周期性的执行规定的定时任务。

3. 四种线程池对象弊端

使用阿里Java开发者规范中的介绍:

  1. FixedThreadPool 和 SingleThreadPool:
    允许的请求队列长度为 Integer.MAX_VALUE,可能会堆积大量的请求,从而导致 OOM。
  2. CachedThreadPool 和 ScheduledThreadPool:
    允许的创建线程数量为 Integer.MAX_VALUE, 可能会创建大量的线程,从而导致 OOM。

4. 线程池的创建

阿里大大的Java开发规范中介绍说线程池不允许使用Executors去创建,而是通过ThreadPoolExecutor的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。所以文章最后介绍一下ThreadPoolExecutor创建线程池。
构造方法:
public ThreadPoolExecutor(intcorePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable>workQueue, RejectedExecutionHandlerhandler)
解释:

  1. corePoolSize:运行任务的核心线程数,如果当前线程数等于核心线程数,则多余的任务会放到等待队列。
  2. maximumPoolSize:最大线程数。测试发现,当等待队列中任务满,且当前任务数<最大线程数,则会新开一个线程。
  3. keepAliveTime:线程池中线程所允许的空闲时间
  4. unit:线程池维护线程所允许的空闲时间的单位(NANOSECONDS、MICROSECONDS、MILLISECONDS、SECONDS等)
  5. workQueue:线程池所使用的缓冲队列
  6. handler:线程池对拒绝任务的处理策略。当缓存队列满,且当前线程数达到了最大线程数(maxmumPoolSize),则会采取拒绝策略。

代码:

import java.util.concurrent.*;

/**
 * ThreadPoolExecutor创建线程池
 */
public class ExecutorThreadPool {

    public static void main(String[] args) {
        ThreadPoolExecutor executorService = new ThreadPoolExecutor(2,10,1, TimeUnit.MINUTES, new LinkedBlockingDeque<>());
        for (int i = 0; i < 100; i++) {
            FutureTask futureTask = new FutureTask(new MyExecutorThread());
            // 提交任务
            executorService.submit(futureTask);
        }
        // 关闭线程池
        executorService.shutdown();
    }
}

class MyExecutorThread implements Callable {

    @Override
    public Object call() throws Exception {
        System.out.println("Thread: " + Thread.currentThread().getName() + " begin...");
        Thread.sleep(5 * 1000);
        System.out.println("Thread: " + Thread.currentThread().getName() + " end...");
        return null;
    }
}

文章源代码地址:https://github.com/Grrui/executor

相关文章

  • Java线程池的使用

    线程类型: 固定线程 cached线程 定时线程 固定线程池使用 cache线程池使用 定时调度线程池使用

  • java----线程池

    什么是线程池 为什么要使用线程池 线程池的处理逻辑 如何使用线程池 如何合理配置线程池的大小 结语 什么是线程池 ...

  • spring 线程池和java线程池

    jdk线程池就是使用jdk线程工具类ThreadPoolExecutor 创建线程池spring线程池就是使用自己...

  • Spring @Async开启异步任务

    定义线程池 使用线程池

  • 八、线程池剖析

    一、前置问题 线程的状态转换 为什么要使用线程池 线程池的继承体系 线程池使用的场景 线程数的设置规则 线程池的状...

  • 1203-AsyncTask详解一:线程池的基本设置

    AsyncTask的内部使用线程池处理并发,要了解它是怎样使用线程池的,那要先了解线程池的基本设置 线程池的基本参...

  • ExecutorService shutdown()和shutd

    ExecutorService是我们经常使用的线程池,当我们使用完线程池后,需要关闭线程池。ExecutorSer...

  • java 线程池使用和详解

    线程池的使用 构造方法 corePoolSize:线程池维护线程的最少数量 maximumPoolSize:线程池...

  • java线程池

    线程VS线程池 普通线程使用 创建线程池 执行任务 执行完毕,释放线程对象 线程池 创建线程池 拿线程池线程去执行...

  • Android中的线程池

    前言 提到线程池,我们先说一下使用线程池的好处。使用线程池的优点可以概括为:1、重复使用线程池中的线程,避免因为线...

网友评论

      本文标题:线程池的使用

      本文链接:https://www.haomeiwen.com/subject/fngfiftx.html