Java多线程-新特性-线程池

Sun在Java5中,对Java线程的类库作了大量的扩展,其中线程池就是Java5的新特征之一,除了线程池以外,还有不少多线程相关的内容,为多线程的编程带来了极大便利。为了编写高效稳定可靠的多线程程序,线程部分的新增内容显得尤其重要。

有关Java5线程新特征的内容所有在java.util.concurrent下面,里面包含数目众多的接口和类,熟悉这部分API特征是一项艰难的学习过程。目前有关这方面的资料和书籍都少之又少,大部分介绍线程方面书籍还停留在java5以前的知识层面上。java

在Java5以前,要实现一个线程池是至关有难度的,如今Java5为咱们作好了一切,咱们只须要按照提供的API来使用,便可享受线程池带来的极大便利。编程

线程池的基本思想仍是一种对象池的思想,开辟一块内存空间,里面存放了众多(未死亡)的线程,池中线程执行调度由池管理器来处理。当有线程任务时,从池中取一个,执行完成后线程对象归池,这样能够避免反复建立线程对象所带来的性能开销,节省了系统的资源。
缓存

Java5提供5种类型的线程池,分别以下:服务器

一:newCachedThreadPool-可变尺寸的线程池(缓存线程池) 
(1)缓存型池子,先查看池中有没有之前创建的线程,若是有,就reuse(重用),若是没有,就创建一个新的线程加入池中; 
(2)缓存型池子,一般用于执行一些生存周期很短的异步型任务;所以一些面向链接的daemon型server中用得很少; 
(3)能reuse(重用)的线程,必须是timeout IDLE内的池中线程,缺省timeout是60s,超过这个IDLE时长,线程实例将被终止及移出池; 
(4)注意,放入CachedThreadPool的线程没必要担忧其结束,超过TIMEOUT不活动,其会自动被终止。多线程

二:newFixedThreadPool-固定大小的线程池 
(1)newFixedThreadPool与cacheThreadPool差很少,也是能reuse就用,但不能随时建新的线程; 
(2)其独特之处:任意时间点,最多只能有固定数目的活动线程存在,此时若是有新的线程要创建,只能放在另外的队列中等待,直到当前的线程中某个线程终止直接被移出池子; 
(3)和cacheThreadPool不一样,FixedThreadPool没有IDLE机制(可能也有,但既然文档没提,确定很是长,相似依赖上层的TCP或UDP IDLE机制之类的),因此FixedThreadPool多数针对一些很稳定很固定的正规并发线程,多用于服务器; 
(4)从方法的源代码看,cache池和fixed池调用的是同一个底层池,只不过参数不一样:
fixed池线程数固定,而且是0秒IDLE(无IDLE);
cache池线程数支持0-Integer.MAX_VALUE(显然彻底没考虑主机的资源承受能力),60秒IDLE。并发

三:ScheduledThreadPool-调度线程池 
(1)调度型线程池; 
(2)这个池子里的线程能够按schedule依次delay执行,或周期执行。异步

四:SingleThreadExecutor-单例线程池 
(1)单例线程,任意时间池中只能有一个线程; 
(2)用的是和cache池和fixed池相同的底层池,但线程数目是1-1,0秒IDLE(无IDLE)。ide

package cn.thread;

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

/**
 * 线程池用法
 * 
 * @author 林计钦
 * @version 1.0 2013-7-25 上午10:00:46
 */
public class ThreadPoolTest {
    public static void main(String[] args) {
        ThreadPoolTest test=new ThreadPoolTest();
        
        //建立一个可重用固定线程数的线程池 
        ExecutorService pool = Executors.newFixedThreadPool(2); 
        //建立实现了Runnable接口对象,Thread对象固然也实现了Runnable接口 
        Thread t1 = test.new MyThread(); 
        Thread t2 = test.new MyThread(); 
        Thread t3 = test.new MyThread(); 
        Thread t4 = test.new MyThread(); 
        Thread t5 = test.new MyThread(); 
        //将线程放入池中进行执行 
        pool.execute(t1); 
        pool.execute(t2); 
        pool.execute(t3); 
        pool.execute(t4); 
        pool.execute(t5); 
        //关闭线程池 
        pool.shutdown(); 
    }
    
    class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "正在执行。");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

5、自定义线程池
ThreadPoolExecutor
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue)
参数:
corePoolSize 
核心线程数,核心线程会一直存活,即便没有任务须要处理。当线程数小于核心线程数时,即便现有的线程空闲,线程池也会优先建立新线程来处理任务,而不是直接交给现有的线程处理。
核心线程在allowCoreThreadTimeout被设置为true时会超时退出,默认状况下不会退出。性能

maximumPoolSize
当线程数大于或等于核心线程,且任务队列已满时,线程池会建立新的线程,直到线程数量达到maxPoolSize。若是线程数已等于maxPoolSize,且任务队列已满,则已超出线程池的处理能力,线程池会拒绝处理任务而抛出异常。学习

keepAliveTime 
当线程空闲时间达到keepAliveTime,该线程会退出,直到线程数量等于corePoolSize。若是allowCoreThreadTimeout设置为true,则全部线程均会退出直到线程数量为0。

unit 
keepAliveTime 参数的时间单位。

workQueue 
执行前用于保持任务的队列。此队列仅保持由 execute 方法提交的 Runnable 任务。

抛出:
IllegalArgumentException - 若是corePoolSize或keepAliveTime小于零,或者maximumPoolSize小于或等于零,或者corePoolSize 大于maximumPoolSize。
NullPointerException - 若是workQueue为null

eg、
//建立等待队列 
BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(20); 
//建立一个单线程执行程序,它可安排在给定延迟后运行命令或者按期地执行。 
ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 3, 2, TimeUnit.MILLISECONDS, queue); 
//建立实现了Runnable接口对象,Thread对象固然也实现了Runnable接口 
Thread t1 = new MyThread(); 
Thread t2 = new MyThread(); 
//将线程放入池中进行执行 
pool.execute(t1); 
pool.execute(t2); 
//关闭线程池 
pool.shutdown();

package cn.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 自定义链接池
 * 
 * @author 林计钦
 * @version 1.0 2013-7-25 上午10:09:17
 */
public class ThreadPoolExecutorTest {

    public static void main(String[] args) {
        ThreadPoolTest test = new ThreadPoolTest();

        // 建立等待队列
        BlockingQueue<Runnable> bqueue = new ArrayBlockingQueue<Runnable>(20);
        // 建立一个单线程执行程序,它可安排在给定延迟后运行命令或者按期地执行。
        ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 3, 2, TimeUnit.MILLISECONDS, bqueue);
        // 建立实现了Runnable接口对象,Thread对象固然也实现了Runnable接口
        Thread t1 = test.new MyThread();
        Thread t2 = test.new MyThread();
        Thread t3 = test.new MyThread();
        Thread t4 = test.new MyThread();
        Thread t5 = test.new MyThread();
        Thread t6 = test.new MyThread();
        Thread t7 = test.new MyThread();
        // 将线程放入池中进行执行
        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);
        pool.execute(t5);
        pool.execute(t6);
        pool.execute(t7);
        // 关闭线程池
        pool.shutdown();
    }

    class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "正在执行。");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
相关文章
相关标签/搜索