javaThreadPool - juedaiyuer/researchNote GitHub Wiki
#java线程池#
如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了,这样频繁创建线程就会大大降低系统的效率,因为频繁创建线程和销毁线程需要时间
##使用线程池的好处##
- 降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的消耗
- 提高响应速度。当任务到达时,任务可以不需要等到线程创建就能立即执行
- 提高线程的可管理性。线程是稀缺资源,如果无限制的创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,调优和监控。但是要做到合理的利用线程池,必须对其原理了如指掌
- 线程池就是Java5的新特征之一
- Java5线程新特征的内容全部在java.util.concurrent
##线程池种类##
- newCachedThreadPool-可变尺寸的线程池(缓存线程池)
- newFixedThreadPool-固定大小的线程池
- ScheduledThreadPool-调度线程池
- SingleThreadExecutor-单例线程池
- ThreadPoolExecutor-自定义线程池
##ThreadPoolExecutor##
- java.util.concurrent.ThreadPoolExecutor
##线程池的使用##
#线程池的创建
new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,milliseconds,runnableTaskQueue, handler);
public static ExecutorSevice newSingleThreadExecutor()
public static ExecutorSevice newFixedThreadPool()
public static ExecutorSevice newCachedThreadPool()
Executor executor = Executors.newSingleThreadExecutor();
executor.execute(new Runnable(){
public void run(){
//执行的任务
}
}
##线程池使用实例##
package thread;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FixedThreadPool {
public static List<Double> queue;
public ExecutorService threadPool;
public FixedThreadPool() {
queue = new ArrayList<Double>();
//产生一个 ExecutorService 对象,这个对象带有一个大小为 poolSize 的线程池,若任务数量大于 poolSize ,任务会被放在一个 queue 里顺序执行。
threadPool = Executors.newFixedThreadPool(5);
}
public static void main(String[] args) {
FixedThreadPool outer = new FixedThreadPool();
FixedThreadPool.Manager inner = outer.new Manager();
Thread consumer = new Thread(inner);
Thread producer = new Thread() {//用于向queue中放入数据
public void run() {
while (true) {
synchronized (queue) {
double time = 1d;
long startTime = System.currentTimeMillis();
if (System.currentTimeMillis() - startTime >= time) {
startTime = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
queue.add((Math.random() * 10000));
}
queue.notify();
}
}
}
}
};
consumer.start();//启动守护线程,采用线程池来从queue中读取数据
producer.start();
}
class Manager implements Runnable {
int num = 0;
public void run() {
while (true) {
try {
synchronized (queue) {
System.out.println("队列的长度为:" + queue.size());
while (queue.isEmpty()) {
queue.wait();
}
double result = queue.remove(0);
num++;
System.out.println("成功从队列中取到数据!" + num);
threadPool.execute(new ExecutorThread(result));
}
} catch (InterruptedException t) {
break;
}
}
threadPool.shutdown();
}
}
class ExecutorThread implements Runnable {
private double value;
public ExecutorThread(double value) {
this.value = value;
}
public void run() {
System.out.println("This is " + Thread.currentThread().getName() + " " + value);
}
}
}
##source##