簡體   English   中英

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

[英]Exactly what a Thread Pool in Java doing?

線程池像任何ExecutorServices一樣,我們定義了一個大小為3的newFixedPool。現在我有一個大約10000個可運行任務的隊列。 為了執行上述過程,我有這些疑慮 -

  1. 要執行上述過程,執行程序是否只允許任務中的3個線程一次運行?

  2. 池將攜帶3個線程,這3個線程將只負責執行所有10000個任務。 如果它是正確的,單個線程如何運行不同的可運行任務,因為最終這些任務也是線程本身,並且在運行任何作業/任務的過程中,您可以為池線程分配新的職責。

  1. 是的,如果實際上你使用的是Executors.newFixedThreadPool(3)那么一次最多只有3個線程會在池中。

  2. 10,000個任務不是Threads它們只是Runnables Thread必須通過Thread#start才能實際創建系統線程。 任務( Runnable實例)放在BlockingQueue 線程池中的線程將輪詢BlockingQueue以運行任務。 當他們完成任務時,他們返回隊列以獲得另一個任務。 如果添加了更多任務,則根據該隊列的實現規則將它們插入到BlockingQueue 對於大多數隊列來說,這是先進先出,但是PriorityQueue實際上使用Comparator或自然排序來在插入任務時對其進行排序。

下面是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;  
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM