现在的位置: 首页 > 综合 > 正文

java 一个简单的线程池

2017年08月09日 ⁄ 综合 ⁄ 共 1257字 ⁄ 字号 评论关闭

本文给大家介绍一个简单的线程池的实现过程,方便大家对线程池的理解。

ThreadPool类如下:

public class ThreadPool
{
    static int MAX_THREAD = 1000;
    static int MIN_THREAD = 14;
    static int id = 1; //线程 ID 号,主要用于监视线程的工作情况
    static private ThreadPool pool = new ThreadPool();

    static public ThreadPool getThreadPool()
    {
        return pool;
    }

    Stack<WorkThread> stack = new Stack<WorkThread>();

    private ThreadPool()
    {
    }

    synchronized public boolean putWorkThread(WorkThread wt)
    {
        if (stack.size() < MIN_THREAD)
        {
            stack.push(wt);
            return true;
        }
        else
        {
            return false;
        }
    }

    synchronized public WorkThread getWorkThread()
    {
        WorkThread wt = null;
        if (stack.isEmpty())
        {
            wt = new WorkThread(this);
            new Thread(wt, "线程ID:" + id).start();
            id++;
        }
        else
        {
            wt = stack.pop();
        }
        return wt;
    }
}

WorkThread类为工作线程,代码如下:

public class WorkThread implements Runnable
{
    Object lock = new Object();
    Runnable runner = null;
    ThreadPool pool = null;

    public WorkThread(ThreadPool pool)
    {
        this.pool = pool;
    }

    public void start(Runnable r)
    {
        runner = r;
        synchronized (lock)
        {
            lock.notify();
        }
    }

    public void run()
    {
        while (true)
        {
            if (runner != null)
            {
                runner.run();
                runner = null; //及时回收资源
            }
            if (pool.putWorkThread(this))
            {
                System.out.println(Thread.currentThread().getName() + " 被回收!");
                synchronized (lock)
                {
                    try
                    {
                        lock.wait();
                    }
                    catch (InterruptedException ie)
                    {
                        System.out.println("停止线程时出现异常");
                    }
                }
            }
            else
            {
                System.out.println(Thread.currentThread().getName() + " 被丢弃!");
                break;
            }
        }
    }
}

转载自:http://www.strutshome.com/index.php/archives/710

抱歉!评论已关闭.