最近在看concurrent下ExecutorService的线程池,感觉不是很好理解,我感觉线程池里面存储的线程应该是对同一类的操作
,但是ExecutorService确可以放入不同的线程,感觉就没有池的概念了。
对比一下一些旧的线程池和 ExecutorService。public class OldThreadPools { public Worker[] workers;
public Vector taskList = new Vector(); public OldThreadPools(int poolNumber) {
workers  =new Worker[poolNumber];
for (int i = 0; i < poolNumber; i++) {
Worker t = new Worker(taskList);
workers[i] = t;
t.run();
}
} public void addTaks(Object o) {
taskList.add(o);
getIdleWorker().run();
} public Worker getIdleWorker() {
// find ide thread
return workers[0];
}
public static void main(String args[]) throws InterruptedException {  
OldThreadPools pool = new OldThreadPools(2);
pool.addTaks("just a test");
}
}class Worker implements Runnable {
List taskList; public Worker(List taskList) {
this.taskList = taskList;
} public void run() {
if (this.taskList!= null && this.taskList.size() > 0) {
Object o = taskList.get(0);
dbOperate(o);
}
} private void dbOperate(Object o) {
 System.out.println("I am db operate thread from pool");
}

}
=================================
public class ExecutorSample { public static void main(String args[]) throws InterruptedException {  
ExecutorService exec = Executors.newFixedThreadPool(2);  
exec.submit(new FileThread());
exec.submit(new DbThread());
exec.shutdown();
}
} class FileThread implements Runnable{
 public void run(){
 System.out.println("I am search file thread");
 }
 }
 class DbThread  implements Runnable{
 public void run(){
 System.out.println("I am db operate thread");
 }
 }
我有以下疑问:
1.自己写的线程池是把一组线程初始化了,有任务的时候取出空闲的线程 ,用完了就放回池中
2.ExecutorService确是把不同的线程放入池中,这些线程对应的操作是不一样的,感觉就是一个运行线程的容器,concurrent如何体现出池的特点?
有人能说说concurrent的设计思想嘛,我总感觉ExecutorService很难理解?

解决方案 »

  1.   

    ExecutorService exec = Executors.newFixedThreadPool(2);  
    这里面有2个工作线程在线程池里面。
    跟workers  =new Worker[poolNumber];
    是一个道理。exec.submit(new FileThread());
    exec.submit(new DbThread());
    这是在执行两个不同的任务。
      

  2.   


    那 Executor 执行完后是否会把当前执行过的线程存储起来? Executor下次如何取空闲线程?
      

  3.   


    什么叫“工作线程”,什么叫“任务”?能区分的开吗?工作线程就是worker,你开的公司,工人干完活就解聘了?干完一个任务以后,工人还会接着做下一个任务,这才是线程池啊!而不是干完一个任务,就把工人解聘,来了活再去招聘一个新工人。比如你有两个工人,两个任务,有一个工人干完活了,那他就空闲了啊!很难理解吗?