7

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

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);  

                }  
            });  
        }   


    }  


}

executor.prestartAllCoreThreads();除非我在构造函数中取消注释或调用execute打印的可运行文件System.out.println("++++++++++++++");(它也被注释掉) ,否则这段代码不会做任何事情。

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

默认情况下,即使是核心线程也只会在新任务到达时才最初创建和启动,但这可以使用方法 prestartCoreThread() 或 prestartAllCoreThreads() 动态覆盖。如果您使用非空队列构造池,您可能希望预启动线程。

行。所以我的队列不是空的。但是我创建了s ,然后我将新executor的s 添加到队列中(在循环中到 100)。 这个循环不算吗? 为什么它不起作用,我必须要么或明确地打电话?sleepRunnable
new tasks arrive
prestartexecute

4

2 回答 2

10

当任务通过执行到达时产生工作线程,这些是与底层工作队列交互的线程。如果您从非空工作队列开始,则需要预先启动工作人员。请参阅OpenJDK 7 中的实现

我再说一遍,工作人员是与工作队列交互的人。它们仅在通过时按需生成execute。(或它上面的层,例如invokeAllsubmit等)如果它们没有启动,那么添加到队列中的工作量无关紧要,因为没有任何工作人员开始检查它。

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);
}
于 2012-08-05T21:23:08.473 回答
5

BlockingQueue 不是一个神奇的线程调度程序。如果你将 Runnable 对象提交到队列中,并且没有正在运行的线程来消费这些任务,那么它们当然不会被执行。另一方面,如果需要,execute 方法会根据线程池配置自动调度线程。如果你预先启动了所有的核心线程,那里就会有线程来消费队列中的任务。

于 2012-08-05T21:43:44.757 回答