读书人

Java中使用Executors来建立Thread pool

发布时间: 2012-08-25 10:06:20 作者: rapoo

Java中应用Executors来建立Thread pool

有时候您需要建立一堆Thread来执行一些小任务,然而频繁的建立Thread有时会是个开销,因为Thread的建立必须与作业系统互动,如果能建立一个Thread pool来管理这些小的Thread并加以重复使用,对于系统效能会是个改善的方式。

您可以使用Executors来建立Thread pool,Executors有几个static方法,列出如下:?

方法说明newCachedThreadPool建立可以快取的Thread,每个Thread预设可idle 60秒

newSingleThreadExecutor

只有一个Thread,循序的执行指定给它的每个任务newScheduledThreadPool可排程的ThreadnewSingleThreadScheduledExecutor单一可排程的Thread
举个简单的实例,下面的程式使用newFixedThreadPool方法建立Thread pool,当中包括五个可以重复使用的Thread,您可以指定Runnable物件给它,程式中会产生十个Runnable物件,由于Thread pool中只有五个可用的Thread,所以后来建立的五个Runnable必须等待有空闲的Thread才会被执行:
读书人网 >编程

热点推荐