I thought that using ThreadPoolExecutor , we can send Runnable to execute either in the BlockingQueue passed in the constructor, or using the execute method.
I also realized that if the task is available, it will be completed.
I do not understand the following:
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); } }); } } }
This code does nothing unless I uncomment executor.prestartAllCoreThreads(); in the OR constructor, I call execute from runnable, which prints System.out.println("++++++++++++++"); (he is also commented).
Why?
Quote (my emphasis):
By default, even the main threads are created at first, and only starts when new tasks arrive , but this can be redefined dynamically using the prestartCoreThread () or prestartAllCoreThreads () method. You probably want to create threads if you create a pool with a non-empty queue.
Ok Therefore, my turn is not empty. But I create an executor , I do sleep , and then add a new Runnable to the queue (in a loop of up to 100).
This loop does not count as new tasks arrive ?
Why doesn't this work, and should I either prestart or explicitly call execute ?