Exactly which thread pool in Java works?

Thread pool, like any ExecutorServices, we defined newFixedPool size 3. Now I have a queue of 10,000 executable tasks. To complete the above process, I have these doubts -

  • To execute the process described above, the executor will allow only 3 threads from the task queue to be launched with one shot?

  • The pool will store 3 threads, and these 3 threads will only be responsible for all 10,000 tasks. If this is correct, then how different tasks are performed in one thread, since ultimately these tasks are also the threads themselves, and in the middle of any task / task, you can assign a new responsibility to the pool thread.

+3
source share
2
  • , , Executors.newFixedThreadPool(3)

  • 10 000 Threads, Runnables. A Thread Thread#start, . ( Runnable) BlockingQueue. BlockingQueue . , , . , BlockingQueue . First-In-First-Out, PriorityQueue Comparator .

+5

ThreadPool java, 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;  
    }
}
0

All Articles