3

他のExecutorServicesと同様に、スレッドプールでは、サイズ3のnewFixedPoolを定義しました。これで、約10000の実行可能なタスクのキューができました。上記のプロセスを実行するために、私はこれらの疑問を持っています-

  1. 上記のプロセスを実行するために、エグゼキュータはタスクのキューから3つのスレッドのみを1回のショットで実行できるようにしますか?

  2. プールは3つのスレッドを実行し、これらの3つのスレッドはすべての10000タスクの実行のみを担当します。それが正しければ、単一のスレッドがさまざまな実行可能なタスクをどのように実行しているか、最終的にそれらのタスクはスレッド自体でもあり、任意のジョブ/タスクの実行中に、プールスレッドに新しい責任を割り当てることができます。

4

2 に答える 2

5
  1. はい、実際に使用している場合、一度にプールに入るスレッドは最大で3つだけです。Executors.newFixedThreadPool(3)

  2. 10,000のタスクはThreads、単なるものではありませんRunnables。実際にシステムスレッドを作成するには、経由Threadで開始する必要があります。Thread#startタスク(のインスタンスRunnable)はに配置されBlockingQueueます。スレッドプールのスレッドは、実行するタスクについてBlockingQueueをポーリングします。タスクを完了すると、キューに戻って別のタスクを取得します。BlockingQueueさらにタスクが追加されると、そのキューの実装のルールに従ってタスクが挿入されます。ほとんどのキューでは、これは先入れ先出しですが、PriorityQueue実際には、Comparator挿入時にタスクを並べ替えるために、または自然な順序を使用します。

于 2012-04-28T05:56:16.007 に答える
0

以下は、noofThreadsとMaxConcurrentTaskを受け入れるJavaのcustomThreadPoolです。また、完全なThreadPoolを停止するためのstop()があります

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;  
    }
}
于 2017-10-10T10:17:14.857 に答える