日期:2014-05-20  浏览次数:20754 次

关于Java线程问题
当一个线程的run方法运行完毕后,线程进入死亡状态。 
死亡状态是指线程从内存清除出去,不符存在了吗? 
线程池中的线程数量是怎么在线程执行Run完毕后保持线程数量不变的?

------解决方案--------------------
死亡状态是指线程从内存清除出去,不符存在了吗? 
——是指线程已经运行结束,线程本身已经消除,但线程对象(new Thread())还在;如果没有任何变量引用,则会被GC所回收。

线程池中的线程数量是怎么在线程执行Run完毕后保持线程数量不变的?
——线程池其实并不存在你说的:“run运行结束”,因为它会永远保证线程的run()永远不运行完毕,只不过是在等待任务而已,看如下事宜代码可能你就明白了:

Java code

public class WorkQueue{
    private final int nThreads;
    private final PoolWorker[] threads;
    private final LinkedList queue;
    public WorkQueue(int nThreads) {
        this.nThreads = nThreads;
        queue = new LinkedList();
        threads = new PoolWorker[nThreads];
        for (int i=0; i<nThreads; i++) {
            threads[i] = new PoolWorker();
            threads[i].start();
        }
    }
    public void execute(Runnable r) { // 你用此函数来提交任务
        synchronized(queue) {
            queue.addLast(r);
            queue.notify();
        }
    }
    private class PoolWorker extends Thread { // 这是线程池中的工作线程
        public void run() {
            Runnable r;
            while (true) { // 死循环,工作线程永远在工作
                synchronized(queue) {
                    while (queue.isEmpty()) { // 从队列中获取任务,直到获取到任务
                        try {
                            queue.wait();
                        }
                        catch (InterruptedException ignored){
                        }
                    }
                    r = (Runnable) queue.removeFirst(); // 取出该任务
                }
                // If we don't catch RuntimeException, 
                // the pool could leak threads
                try {
                    r.run(); // 执行该任务
                }
                catch (RuntimeException e) {
                    // You might want to log something here
                }
            }
        }
    }
}