如果一味的new Thread,不用线程池,可能会导致同时执行很多线程,引发性能问题。比如在ListView里,每个item都有一张网络图片,如果在adapter里的getView方法里直接使用new Thread去异步下载图片,当划动listview时,如果速度快,就会产生几十甚至上百个下载线程。而使用线程池,就可以很方便管理线程。 代码来自Think in Java。 LiftOff.java:
package com.test;
public class LiftOff implements Runnable{
protected int countDown=10;
private static int taskCount=0;
private final int id=taskCount++;
public LiftOff() {
System.out.println("#"+id+" created");
}
public LiftOff(int countDown)
{
this.countDown=countDown;
}
public String status()
{
return "#"+id+"("+(countDown>0?countDown:"Liftoff")+").";
}
@Override
public void run()
{
while(countDown-->0)
{
System.out.println(status());
}
System.out.println("#"+id+" destory");
}
}
package com.test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
//使用线程池管理线程,FixedThreadPool是一个限制线程数量的线程池,参数是线程数量
//任何线程池,在有可能的情况下,现有线程会被利用
ExecutorService exec=Executors.newFixedThreadPool(1);
for(int i=0;i<2;i++)
{
exec.execute(new LiftOff());
}
exec.shutdown();
}
}
看执行的结果: #0 created #1 created #0(9). #0(8). #0(7). #0(6). #0(5). #0(4). #0(3). #0(2). #0(1). #0(Liftoff). #0 destory #1(9). #1(8). #1(7). #1(6). #1(5). #1(4). #1(3). #1(2). #1(1). #1(Liftoff). #1 destory
可以看到,所有的LiftOff先构造完,然后再一个线程一个线程执行,因为我们限制了只能同时有一个线程。另外,SingleThreadExecutor就是线程数量为1的FixedThreadPool