ThreadPoolExecutor和队列

Cra*_*lus 6 java concurrency multithreading java.util.concurrent threadpoolexecutor

我认为使用ThreadPoolExecutor我们可以提交Runnables BlockingQueue在构造函数中传递或使用execute方法执行.
另外我的理解是,如果任务可用,它将被执行.
我不明白的是以下内容:

public class MyThreadPoolExecutor {  

    private static ThreadPoolExecutor executor;  

    public MyThreadPoolExecutor(int min, int max, int idleTime, BlockingQueue<Runnable> queue){  
        executor = new ThreadPoolExecutor(min, max, 10, TimeUnit.MINUTES, queue);   
        //executor.prestartAllCoreThreads();  
    }  

    public static void main(String[] main){
        BlockingQueue<Runnable> q = new LinkedBlockingQueue<Runnable>();
        final String[] names = {"A","B","C","D","E","F"};  
        for(int i = 0; i < names.length; i++){  
            final int j = i;  
            q.add(new Runnable() {  

                @Override  
                public void run() {  
                    System.out.println("Hi "+ names[j]);  

                }  
            });         
        }  
        new MyThreadPoolExecutor(10, 20, 1, q);   
        try {  
            TimeUnit.SECONDS.sleep(5);  
        } catch (InterruptedException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        /*executor.execute(new Runnable() {  

            @Override  
            public void run() {  

                System.out.println("++++++++++++++");  

            }   
        });  */
        for(int i = 0; i < 100; i++){  
            final int j = i;  
            q.add(new Runnable() {   

                @Override  
                public void run() {  
                    System.out.println("Hi "+ j);  

                }  
            });  
        }   


    }  


}
Run Code Online (Sandbox Code Playgroud)

除非我executor.prestartAllCoreThreads();在构造函数中取消注释或者调用executeprintn的runnable System.out.println("++++++++++++++");(它也被注释掉),否则这段代码不会做任何事情.

为什么?
引用(我的重点):

默认情况下,甚至核心线程最初只在新任务到达时创建并启动,但可以使用方法prestartCoreThread()或prestartAllCoreThreads()动态覆盖.如果使用非空队列构造池,则可能需要预启动线程.

好.所以我的队列不是空的.但是我创建了executor,我这样做sleep然后我将新的Runnables 添加到队列中(在循环中为100).
这个循环算不算new tasks arrive
为什么它不起作用我必须要么prestart明确地打电话execute

old*_*inb 9

当执行任务到达时,将生成工作线程,这些是与底层工作队列交互的线程.如果以非空工作队列开始,则需要预启动工作程序.请参阅OpenJDK 7中实现.

我再说一遍,工人是与工作队列互动的工人.它们只是在通过时按需生成execute.(或者它上面的层,例如invokeAll,submit等等)如果它们没有启动,那么添加到队列中的工作量并不重要,因为没有任何工作人员启动时没有检查它.

ThreadPoolExecutor在必要之前或者通过prestartAllCoreThreadsprestartCoreThread方法预先创建它们的创建时,不会生成工作线程.如果没有工作人员启动,那么您的队列中的任何工作都无法完成.

添加初始execute作品的原因是它强制创建唯一的核心工作线程,然后该线程可以开始处理队列中的工作.您也可以呼叫prestartCoreThread和接收类似的行为.如果要启动所有工作人员,则必须通过以下方式呼叫prestartAllCoreThreads或提交该数量的任务execute.

请参阅execute下面的代码.

/**
 * Executes the given task sometime in the future.  The task
 * may execute in a new thread or in an existing pooled thread.
 *
 * If the task cannot be submitted for execution, either because this
 * executor has been shutdown or because its capacity has been reached,
 * the task is handled by the current {@code RejectedExecutionHandler}.
 *
 * @param command the task to execute
 * @throws RejectedExecutionException at discretion of
 *         {@code RejectedExecutionHandler}, if the task
 *         cannot be accepted for execution
 * @throws NullPointerException if {@code command} is null
 */
public void execute(Runnable command) {
    if (command == null)
        throw new NullPointerException();
    /*
     * Proceed in 3 steps:
     *
     * 1. If fewer than corePoolSize threads are running, try to
     * start a new thread with the given command as its first
     * task.  The call to addWorker atomically checks runState and
     * workerCount, and so prevents false alarms that would add
     * threads when it shouldn't, by returning false.
     *
     * 2. If a task can be successfully queued, then we still need
     * to double-check whether we should have added a thread
     * (because existing ones died since last checking) or that
     * the pool shut down since entry into this method. So we
     * recheck state and if necessary roll back the enqueuing if
     * stopped, or start a new thread if there are none.
     *
     * 3. If we cannot queue task, then we try to add a new
     * thread.  If it fails, we know we are shut down or saturated
     * and so reject the task.
     */
    int c = ctl.get();
    if (workerCountOf(c) < corePoolSize) {
        if (addWorker(command, true))
            return;
        c = ctl.get();
    }
    if (isRunning(c) && workQueue.offer(command)) {
        int recheck = ctl.get();
        if (! isRunning(recheck) && remove(command))
            reject(command);
        else if (workerCountOf(recheck) == 0)
            addWorker(null, false);
    }
    else if (!addWorker(command, false))
        reject(command);
}
Run Code Online (Sandbox Code Playgroud)

  • 只要工作线程等待消耗工作,您就可以通过队列进行交互,因此文档建议您为非空工作队列预先启动它们.通过调用`execute`来"启动"执行程序只会启动一个worker,即不是整个池. (2认同)

Bla*_*ain 5

BlockingQueue不是魔术线程调度程序.如果您将Runnable对象提交到队列并且没有正在运行的线程来使用这些任务,那么它们当然不会被执行.另一方面,如果需要,execute方法将根据线程池配置自动分派线程.如果您预先启动所有核心线程,则会有线程从队列中消耗任务.