原创

多线程创建之线程池

利用线程池创建的优点:

1.提高响应速度(减少了创建新线程的时间)

2.降低资源消耗(重复利用线程池中线程,不需要每次都创建)

3.便于线程管理:

     corePoolSize:核心池的大小

     maximumPooSize: 最大的线程数

     keepAliveTime: 线程没有任务时最多保持长时间会终止


线程池的体系结构:

java.util.concurrent.Executor : 负责线程的使用与调度的根接口

    | -- ExecutorService 子接口:线程池的主要接口

        | -- ThreadPoolExecutor 线程池的实现类  

        | -- ScheduledExecutorService 子接口: 负责线程的调度

            | -- ScheduledThreadPoolExecutor :继承ThreadPoolExecutor,实现ScheduledExecutorService



相关的API:ExecutorService 和 Executors

ExecutorService: 真正的线程池接口。常见子类ThreadPoolExecutor

1.void execute(Runnable runnable): 执行任务/命令,没有返回值,一般用来执行Runnable

2.<T> Future <T> submit(Callable<T> task) : 执行任务,有返回值,一般用来执行Callable

3.void shutdown(): 关闭连接池

Executors: 工具类,线程池的工厂类,用于创建并返回不同类型的线程池

1.Executors.newCachedThreadPool(): 创建一个可根据需要创建新线程的线程池

2.Executors.newFixedThreadPool(n): 创建一个可重用固定线程数的线程池

3.Executors.newSingleThreadExecutor():创建一个只有一个线程的线程池

4.Executors.newScheduledThreadPool(n): 创建一个线程池,它可安排在给定延迟后运行命令或者定期地执行。


示例代码:

package com.debuggg.exer;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

class NumThread2 implements Runnable {

@Override
public void run() {
int sum = 0;
for (int i = 0; i < 100; i++) {
if(i % 2 == 0){
sum += i;
System.out.println(i);
}
}
}
}

public class ThreadPoolExecuterTest {

public static void main(String[] args) {
//1.提供指定线程数量的线程池
ExecutorService service = Executors.newFixedThreadPool(10);

//2.设置线程池的属性
ThreadPoolExecutor executor = (ThreadPoolExecutor) service;
executor.setCorePoolSize(15);
// executor.setKeepAliveTime();

//3.执行指定的线程的操作,需要提供实现Runnable接口或Callable接口实现类的对象
service.execute(new NumThread2());
// service.submit(new CallableTest());

//4.关闭连接池
service.shutdown();
}

}


另外,提供一个获取线程池的单例模式,双重检查形式:

代码如下:

package com.cyjz.util;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
* Created by 28061 on 2018/2/5.
* @author wangrui
* @content 单例FixedThreadPool线程池的构建
*/
public class SingleThreadPool {
private static Pool mThreadPool;


// 获取单例的线程池对象
public static Pool getInstance() {
if (mThreadPool == null) {
synchronized (SingleThreadPool.class) {
if (mThreadPool == null) {
int cpuNum = Runtime.getRuntime().availableProcessors();// 获取处理器数量
int threadNum = cpuNum * 2 + 1;// 根据cpu数量,计算出合理的线程并发数
mThreadPool = new Pool(threadNum, threadNum, 0L);
}
}
}
return mThreadPool;
}

public static class Pool {

private ThreadPoolExecutor mexecutor;
private int corepoolsize;
private int maximumpoolsize;
private long keepalivetime;

private Pool(int corepoolsize, int maximumpoolsize, long keepalivetime){
this.corepoolsize = corepoolsize;
this.maximumpoolsize = maximumpoolsize;
this.keepalivetime = keepalivetime;
}

public void execute(Runnable runnable){

if (runnable == null){
return;
}
if (mexecutor == null){
mexecutor = new ThreadPoolExecutor(corepoolsize, //核心线程数
maximumpoolsize, //最大线程数
keepalivetime, //闲置线程存活时间
TimeUnit.MILLISECONDS, // 时间单位
new LinkedBlockingDeque<Runnable>(), //线程队列
Executors.defaultThreadFactory(), //线程工厂
new ThreadPoolExecutor.AbortPolicy() //队列已满,而且当前线程数已经超过最大线程数时的异常处理策略
);
}
mexecutor.execute(runnable);
}

public void cancel(Runnable runnable){
if(mexecutor != null){
mexecutor.getQueue().remove(runnable);
}
}

}
}



正文到此结束
本文目录