java线程池的实现原理

什么是线程池,换一句通俗的话来讲,就是创建若干个worker线程,在线程中执行死循环来获取任务并执行,这个死循环可以通过isinterrupt()来作为是否退出的标志

在死循环中,如果获取到任务就执行,没有任务就阻塞(wait),不能使sleep,想想sleep和wait的区别就知道:

三,实现


  1)线程池管理类
  
package poolmanager;

 /**
 * ThreadPoolManager 线程池管理类
 * @version 1.0.0
 * @see 线程池定义式样书
 * @date    2011/09/30 IterZebra
 */
//import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import systemconfig.SystemConfig;

public class ThreadPoolManager extends ThreadGroup {

    /**线程池是否开启标识*/
    int flagThreadPoolValid = 0;

    /**线程池中线程的数量,从系统配置类中获取*/
    int threadSize = SystemConfig.getThreadDefaultCount();

    /**任务队列*/
     /**
     Java 2 SE Documentation.
     Returns a synchronized (thread-safe) list backed by the specified list.
     In order to guarantee serial access, it is critical that all access to
     the backing list is accomplished through the returned list.
     根据指定的参数list,返回一个线程安全的同步的list。
     为了保证有序访问,所有的对于参数list的访问都应该通过返回的这个list去进行。
     It is imperative that the user manually synchronize
     on the returned list when iterating over it.
     如果进行迭代访问的时候,对于返回的队列应用程序本身进行同步处理是必要的。
     注:即使用迭代器访问应该使用synchronized(){}修饰代码块,使得其对list的访问进行同步;
     而如果是采用返回的list的add等方法,则应用程序本身不需要进行同步处理。

     另外由于本类中对ThreadPoolManager的访问方法都进行了同步操作,
     因此对本List的同步不是必要的。
     当然,由于加锁顺序一致性,使用对List的同步,也不会导致线程死锁。
    List TaskList= Collections.synchronizedList(new LinkedList());

    */
    List TaskList= new LinkedList();

    /**线程池管理类构造方法*/
    public ThreadPoolManager(String threadpoolname) {

         //ThreadGroup的名称
        super(threadpoolname);

        //继承自父类的方法,设置是否是守护线程
        setDaemon(true);

    }

    /**
     * @brief 开启线程池
     * @param null
     * @return void
     */
    public synchronized void threadPoolStart(){

        if(threadSize ==0 || flagThreadPoolValid !=0){

            try {
                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
            }

            return ;
        }

        if( TaskList ==null ){

            try {
                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
            }

            return;
        }

        // 创建并开启线程例程
        for (int i = 0;i

你可能感兴趣的:(java线程池,java基础)