线程池和如何用线程池实现wordCount

因为在很多并发代码里看到下面这种形式的代码,对join方法理解不是很清晰,所以在讲解线程池之前先对join方法进行一个简单的记录:

p1.start();
p2.start();
p1.join();
p2.join();

先看一下join方法的源码注释


join

因此,可以这样理解join的作用,在主线程中,线程p1调用了自身的join()方法,通知主线程只有等到p1执行完毕的时候主线程才能继续执行(waits for this thread to die)。

言归正传,进入今天的主题--线程池,线程池,首先分析上层接口 Executor的java源码:

public interface Executor {

    /**
     * Executes the given command at some time in the future.  The command
     * may execute in a new thread, in a pooled thread, or in the calling
     * thread, at the discretion of the {@code Executor} implementation.
     *
     * @param command the runnable task
     * @throws RejectedExecutionException if this task cannot be
     * accepted for execution
     * @throws NullPointerException if command is null
     */
    void execute(Runnable command);
}
  • 接口里只有一个方法,execute, 接收一个Runnable任务;
  • 相比于之前的new Thread(Runnable r).start()方式,隐藏了任务是如何被执行,线程调用和使用的细节,当前任务可能被calling thread执行,也可能在一个新线程内执行,取决于Executor的具体实现。

ExecutorService接口继承接口Executor,并且扩充了更多的方法,包括提交一个任务以后,立刻返回一个Future对象。

<T> Future<T> submit(Callable<T> task);

Future有一个get方法,等待线程计算完毕时,返回计算结果。

 /**
     * Waits if necessary for at most the given time for the computation
     * to complete, and then retrieves its result, if available.
     */
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;

前两个Executor和ExecutorService都是接口,下面的Executors类和ThreadPoolExecutor类是创建线程工厂的类,Executors类提供了创建线程工厂的各种方法,ThreadPoolExecutor类提供了自定义线程池实现方法。

首先介绍Executors类中提供的各种定义好的线程池的创建方法:

  • newFixedThreadPool:创建一个固定线程数量的线程池,线程可以复用,阻塞队列长度为无限大,可能造成内存溢出问题。
public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
  • newSingleThreadExecutor():一个线程工作的线程池
public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }
  • newCachedThreadPool():根据需要创建线程,可以复用之前可用的线程,一个线程在超过60s无任务可执行就会死亡。
 public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

可以看到,Executors类为我们提供了各种创建线程池的方法,面向于不同的应用场景,但是这些线程池创建中的任务队列是无限大的,在任务过多时会造成内存溢出问题,而且可能这些线程池都不能满足我们的需求,这时,我们就可以采用ThreadPoolExecutor类中的方法,通过自己操控五个参数,创建满足自己需求的线程池。

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler)
  • corePoolSize: 线程池中一直维持的最小线程数,即使他们是空闲的;
  • maximumPoolSize:线程池中可以存在的最大线程数;
  • keepAliveTime:当线程池中线程数大于核心线程数时,一个空闲的线程等待新的任务超过keepAliveTime时间,被杀死;
  • unit:时间单位;
  • workQueue:保存任务;
  • threadFactory:线程工厂,将一个Runnable任务转换为一个线程返回;
public interface ThreadFactory {

    /**
     * Constructs a new {@code Thread}.  Implementations may also initialize
     * priority, name, daemon status, {@code ThreadGroup}, etc.
     *
     * @param r a runnable to be executed by new thread instance
     * @return constructed thread, or {@code null} if the request to
     *         create a thread is rejected
     */
    Thread newThread(Runnable r);
}
  • RejectedExecutionHandler handler: 任务过多的时候的拒绝策略:
    AbortPolicy:拒绝并抛出一个异常
/**
     * A handler for rejected tasks that throws a
     * {@code RejectedExecutionException}.
     */
    public static class AbortPolicy implements RejectedExecutionHandler

CallerRunsPolicy: 让调用者执行

/**
     * A handler for rejected tasks that runs the rejected task
     * directly in the calling thread of the {@code execute} method,
     * unless the executor has been shut down, in which case the task
     * is discarded.
     */
    public static class CallerRunsPolicy implements RejectedExecutionHandler

DiscardOldestPolicy:丢弃一个最老的

/**
     * A handler for rejected tasks that discards the oldest unhandled
     * request and then retries {@code execute}, unless the executor
     * is shut down, in which case the task is discarded.
     */
    public static class DiscardOldestPolicy implements RejectedExecutionHandler 

DiscardPolicy:丢弃一个

学习了这么多理论知识,不如实际操作,下面给出了如何用Executors的方法实现wordCount:

package com.github.hcsp.multithread;

import sun.awt.windows.WToolkit;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

public class MultiThreadWordCount1 {
    //使用threadNum个线程,并发统计文件中各单词的数量
    //使用定义好的线程池
    public static Map<String, Integer> count(int threadNum, List<File> files) throws ExecutionException, InterruptedException {
        ExecutorService threadPool = Executors.newFixedThreadPool(threadNum);
        List<Future<Map<String, Integer>>> futures = new ArrayList<>();
        for (File file : files) {
            Future<Map<String, Integer>> future = threadPool.submit(new WordCount(file));
            futures.add(future);
        }
        HashMap<String, Integer> res = new HashMap<>();
        for (Future<Map<String, Integer>> future : futures) {
            HashMap<String, Integer> tmp = (HashMap<String, Integer>) future.get();
            for (String s : tmp.keySet()) {
                res.put(s, res.getOrDefault(s, 0) + tmp.get(s));
            }
        }
        return res;
    }

    static class WordCount implements Callable<Map<String, Integer>> {
        File file;

        WordCount(File file) {
            this.file = file;
        }

        @Override
        public Map<String, Integer> call() throws Exception {
            HashMap<String, Integer> res = new HashMap<>();
            List<String> strings = Files.readAllLines(file.toPath());
            for (String str : strings) {
                for (String st : str.split("\\s+")) {
                    res.put(st, res.getOrDefault(st, 0) + 1);
                }
            }
            return res;
        }
    }

}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 198,932评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,554评论 2 375
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 145,894评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,442评论 1 268
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,347评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,899评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,325评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,980评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,196评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,163评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,085评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,826评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,389评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,501评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,753评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,171评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,616评论 2 339