当前位置: 代码迷 >> J2SE >> 线程池 有关问题求教
  详细解决方案

线程池 有关问题求教

热度:9081   发布时间:2013-02-25 21:53:56.0
线程池 问题求教~
本帖最后由 a12939026 于 2013-01-23 15:13:42 编辑

package a.b.threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TpTest {
public static void  main(String[] args){
 BlockingQueue<Runnable> bqueue = new ArrayBlockingQueue<Runnable>(20); 
         
         ThreadPoolExecutor pool = new ThreadPoolExecutor(3,5,20,TimeUnit.MILLISECONDS,bqueue); 
         pool.execute(new XianChen("线程1"));
         pool.execute(new XianChen("线程2"));
         pool.execute(new XianChen("线程3"));
         pool.execute(new XianChen("线程4"));
         pool.execute(new XianChen("线程5"));
         pool.execute(new XianChen("线程6"));
         pool.execute(new XianChen("线程7"));
         pool.execute(new XianChen("线程8"));
         pool.execute(new XianChen("线程9"));
         pool.execute(new XianChen("线程10"));
         pool.execute(new XianChen("线程11"));
         pool.shutdown();
}
}

class XianChen extends Thread{
String name;
XianChen(String name){
this.name = name;
}

public void run() {
System.out.println(Thread.currentThread().getName()+"进入");
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println(Thread.currentThread().getName()+"退出");
}
}


new ThreadPoolExecutor(3,5,20,TimeUnit.MILLISECONDS,bqueue) 这个第二个参数的5 是不是最大的运行数?  我现在有11个线程需要运行, 那应该开放5个线程来处理吧 为何看结果他只开放3个呢? 还是我理解有问题?
thread 线程池
刚看了下,执行时这样
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue)
在这构造方法中,优先级处理任务的优先级为: 
核心线程corePoolSize、任务队列workQueue、最大线程maximumPoolSize。意思是只有当corePoolSize中任务满了,会先放到workQueue缓冲队列中,缓冲队列满了,才会放到maximumPoolSize里面去。
  相关解决方案