究竟是Java中的线程池在做什么?

时间:2012-04-28 05:47:15

标签: java multithreading threadpool

线程池与任何ExecutorServices一样,我们定义了一个大小为3的newFixedPool。现在我有一个大约10000个可运行任务的队列。 为了执行上述过程,我有这些疑虑 -

  1. 要执行上述过程,执行者是否只允许任务中的3个线程一次性运行?

  2. Pool将携带3个线程,这3个线程只负责执行所有10000个任务。如果它是正确的,单个线程如何运行不同的可运行任务,因为最终这些任务也是线程本身,并且在运行任何作业/任务的过程中,您可以为池线程分配新的职责。 / p>

2 个答案:

答案 0 :(得分:5)

  1. 是的,如果实际上您使用的是Executors.newFixedThreadPool(3)

  2. ,则一次最多只有3个主题会在池中
  3. 10,000个任务不是Threads,而只是Runnables。必须通过Thread启动Thread#start才能实际创建系统线程。任务(Runnable的实例)放在BlockingQueue中。线程池中的线程将轮询BlockingQueue以运行任务。当他们完成任务时,他们返回队列以获得另一个任务。如果添加了更多任务,则根据该队列的实现规则将它们插入BlockingQueue。对于大多数队列而言,这是先进先出,但PriorityQueue实际上使用Comparator或自然顺序对插入的任务进行排序。

答案 1 :(得分:0)

以下是java中的customThreadPool,它接受noofThreads和MaxConcurrentTask。 它还有stop()来停止完整的ThreadPool

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;


@SuppressWarnings("all")
public class ThreadPool { 


    private BlockingQueue taskQueue = null;  
    private List<PoolThread> threads = new ArrayList<PoolThread>(); 
    private boolean isStopped = false; 

    public ThreadPool(int noOfThreads, int maxNoOfTasks) { 
        taskQueue = new LinkedBlockingQueue(maxNoOfTasks);
        for(int i=0; i<noOfThreads; i++) {    
            threads.add(new PoolThread(taskQueue));  
        }   

        for(PoolThread thread : threads) {    
            thread.start();  
        }  
    }  

    public synchronized void execute(Runnable task) {  

        if(this.isStopped) 
            throw  new IllegalStateException("ThreadPool is stopped");

        this.taskQueue.offer(task); 
    }  

    public synchronized void stop() {  
        this.isStopped = true;  
        for(PoolThread thread : threads)    {     
            thread.stopMe();   
        } 
    }
}


@SuppressWarnings("all")
class PoolThread extends Thread { 

    private BlockingQueue taskQueue = null; 
    private boolean       isStopped = false; 
    public PoolThread(BlockingQueue queue)  { 
        taskQueue = queue; 
    } 

    public void run()   {   
        while(!isStopped()) {   
            try {    
                Runnable runnable = (Runnable) taskQueue.poll();  
                runnable.run();     
            } catch(Exception e)    {    
                //log or otherwise report exception,        //but keep pool thread alive.  

            }    
        } 
    } 

    public synchronized void stopMe()   {  
        isStopped = true;   
        this.interrupt(); 
        //break pool thread out of dequeue() call. 
    }  

    public synchronized boolean isStopped() {  
        return isStopped;  
    }
}