java多线程 -- 线程池

233 阅读7分钟
原文链接: www.cnblogs.com
西北野狼
我的github: https://github.com/soyoungboy
我的segmentfault: http://segmentfault.com/u/soyoungboy

【不积跬步,无以至千里;不积小流,无以成江海】
博客园   首页   新随笔   联系   订阅 订阅  管理 随笔-477  评论-20  文章-0 

java多线程 -- 线程池

第四种获取线程的方法:线程池,一个 ExecutorService,它使用可能的几个池线程之一执行每个提交的任务,通常使用 Executors 工厂方法配置。

线程池可以解决两个不同问题:由于减少了每个任务调用的开销,它们通常可以在执行大量异步任务时提供增强的性能,并且还可以提供绑定和管理资源(包括执行任务集时使用的线程)的方法。每个 ThreadPoolExecutor 还维护着一些基本的统计数据,如完成的任务数。

为了便于跨大量上下文使用,此类提供了很多可调整的参数和扩展钩子 (hook)。但是,强烈建议程序员使用较为方便的 Executors 工厂方法 :

  1. Executors.newCachedThreadPool()(无界线程池,可以进行自动线程回收)
  2. Executors.newFixedThreadPool(int)(固定大小线程池)
  3. Executors.newSingleThreadExecutor()(单个后台线程)

它们均为大多数使用场景预定义了设置.

线程池封装类(android开发中用过):

package com.company;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @类名: ThreadUtils
 * @描述: TODO(线程池工具类)
 * @作者: soyoungboy
 */
public class ThreadUtils {
    private static volatile ThreadUtils instance = null;

    // private constructor suppresses
    private ThreadUtils() {

    }

    public static ThreadUtils getInstance() {
        // if already inited, no need to get lock everytime
        if (instance == null) {
            synchronized (ThreadUtils.class) {
                if (instance == null) {
                    instance = new ThreadUtils();
                }
            }
        }

        return instance;
    }

    /**
     * 初始化的线程数,有待历史的验证,暂时弄4个
     */
    public ExecutorService threadPool = Executors.newFixedThreadPool(4);

    /**
     * 单线程
     */
    static ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();

    /**
     * 执行延迟任务,类似Timer的效果
     */
    public ScheduledExecutorService scheduleThreadPool = Executors.newScheduledThreadPool(2);

    /**
     * 立即执行任务
     *
     * @param task ThreadUtils.getInstance().excute(run);
     */
    public void excute(Runnable task) {
        threadPool.execute(task);
    }

    /**
     * 单线程持操作,主要用于数据库的读写异步操作
     *
     * @param task ThreadUtils.getInstance().excuteSingleThread(run);
     * @return
     */
    public Future excuteSingleThread(Runnable task) {
        return singleThreadPool.submit(task);
    }

    ;

    /**
     * 延后执行任务
     *
     * @param task
     * @param delay ThreadUtils.getInstance().schedule(run,1000);
     */
    public void schedule(Runnable task, long delay) {
        scheduleThreadPool.schedule(task, delay, TimeUnit.MILLISECONDS);
    }


    /**
     * @return void 返回类型
     * @Title: shutdownThreadPool
     * @Description: TODO()
     */
    public void shutdownThreadPool() {
        threadPool.shutdownNow();
    }

    /**
     * @return void 返回类型
     * @Title: shutdownThreadPool
     * @Description: TODO()
     */
    public void shutdownScheduleThreadPool() {
        scheduleThreadPool.shutdownNow();

    }

    /**
     * @return void 返回类型
     * @Title: shutdownSingleThreadPool
     * @Description: TODO(单线程池销毁操作)
     */
    public void shutdownSingleThreadPool() {
        singleThreadPool.shutdownNow();
    }
}

 

Demo:

public class TestScheduledThreadPool {

    public static void main(String[] args) throws Exception {
        ThreadUtils instance = ThreadUtils.getInstance();
        for (int i = 0; i < 10; i++) {
            instance.schedule(() -> {
                int num = new Random().nextInt(100);//生成随机数
                System.out.println(Thread.currentThread().getName() + " : " + num);
            }, 3);
        }
        instance.shutdownScheduleThreadPool();

    }

}

结果:

pool-3-thread-2 : 79
pool-3-thread-1 : 87
pool-3-thread-2 : 44
pool-3-thread-1 : 90
pool-3-thread-2 : 0
pool-3-thread-1 : 77
pool-3-thread-2 : 20
pool-3-thread-1 : 63
pool-3-thread-2 : 68
pool-3-thread-1 : 15

 

posted on 2017-04-02 23:23 西北野狼 阅读(50) 评论(0) 编辑 收藏 刷新评论刷新页面返回顶部 注册用户登录后才能发表评论,请 登录注册访问网站首页。 【推荐】超50万VC++源码: 大型工控、组态\仿真、建模CAD源码2018!
【推荐】微信小程序一站式部署 多场景模板定制
SpreadJS2_1206 最新IT新闻:
· 你逛的这些地方,可能都是腾讯的地盘
· 你已经习惯了的这些衣食住行,其实都是阿里的地盘
· 华为云总裁郑叶来:公有云竞争远未结束 AI被过度消费
· 扎克伯格纪念FB诞生14周年:你们想到的错误 我都犯过
· A站凉了,百万“猴子”无家可归
» 更多新闻... 阿里云C2-1208 最新知识库文章:
· 领域驱动设计在互联网业务开发中的实践
· 步入云计算
· 以操作系统的角度述说线程与进程
· 软件测试转型之路
· 门内门外看招聘
» 更多知识库文章... 历史上的今天:
2016-04-02 android app 集成 信鸽推送
昵称:西北野狼
园龄: 4年6个月
粉丝:34
关注: 3 +加关注
< 2018年2月 >
28 29 30 31 1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 1 2 3
4 5 6 7 8 9 10

搜索

   

常用链接

我的标签

随笔分类

随笔档案

My github

我的个人博客站点

积分与排名

  • 积分 - 110533
  • 排名 - 2676

最新评论

阅读排行榜

评论排行榜

推荐排行榜

Powered by: 博客园 模板提供:沪江博客 Copyright ©2018 西北野狼