线程池的阻塞队列大小设置为10,
并且用了闭锁,向线程池中加入12个线程,no problem ,可以运行。public class ThreadPoolTwo {
public static void main(String[] args) {

try{
//线程的池阻塞队列。
LinkedBlockingQueue<Runnable> tasks = new LinkedBlockingQueue<Runnable>(
10); ExecutorService pool = new ThreadPoolExecutor(2, 2, 0L,
TimeUnit.MILLISECONDS, tasks);

CountDownLatch begin=new CountDownLatch(1);

for(int i=0;i<12;i++){
TaskOne task=new TaskOne(begin);
pool.submit(task);
}
begin.countDown();
pool.shutdown();
}catch(Exception e){
e.printStackTrace();
}


}
}
class TaskOne implements Runnable{ private CountDownLatch begin;

public TaskOne(CountDownLatch latch){
this.begin=latch;
}

@Override
public void run() {
try {
begin.await();
System.out.println(Thread.currentThread().getName()+"欢迎您");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}
但是向线程池中加入100个线程,就会报错了。public class ThreadPoolTwo {
public static void main(String[] args) {

try{
//线程的池阻塞队列。
LinkedBlockingQueue<Runnable> tasks = new LinkedBlockingQueue<Runnable>(
10); ExecutorService pool = new ThreadPoolExecutor(2, 2, 0L,
TimeUnit.MILLISECONDS, tasks);

CountDownLatch begin=new CountDownLatch(1);

for(int i=0;i<12;i++){
TaskOne task=new TaskOne(begin);
pool.submit(task);
}
begin.countDown();
pool.shutdown();
}catch(Exception e){
e.printStackTrace();
}


}
}
class TaskOne implements Runnable{ private CountDownLatch begin;

public TaskOne(CountDownLatch latch){
this.begin=latch;
}

@Override
public void run() {
try {
begin.await();
System.out.println(Thread.currentThread().getName()+"欢迎您");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}真是奇怪啊,本应该加入的线程超过10个就会报错,为什么加入12个不会报错啊? help

解决方案 »

  1.   

    ThreadPoolExecutor这个对象最好不要自己直接创建,参数很多,不好掌握。
    Executors里有好多定义好的线程池。
    根据javadoc,如果core线程还有空闲,就不会把任务放到阻塞列队了,
    你刚好定义了两个core线程,所以12个是没问题的。
      

  2.   

    同意楼上,13个就不行,ExecutorService只能支持12个任务执行
    说明了任务容量就是队列容量+线程池大小