我正在尝试理解ThreadPoolExecutor类。我已经阅读了这个答案和Javadoc。但是我的实验结果与那个描述不符:
我使用一个工厂初始化线程池以跟踪id。
int tcounter = 0;
ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 4, 1, TimeUnit.MINUTES,
new ArrayBlockingQueue<Runnable>(1000), new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new mThread(tcounter++, r);
}
});
public class mThread extends Thread {
int id;
private mThread(int id, Runnable run) {
super(run);
GLog.e("created thread " + id);
this.id = id;
}
}
然后是任务:
public class mRunanble implements Runnable {
int value = 0;
private mRunanble(int value) {
super();
this.value = value;
}
@Override
public void run() {
SystemClock.sleep(3000);
Thread t = Thread.currentThread();
if (t instanceof mThread) {
GLog.e("Say " + (value) + " on thread " + ((mThread) t).id);
}
}
}
并将操作分配给按钮:
executor.execute(new mRunanble(i++));
但是我一直按那个按钮,第三个线程从未被创建,那么在ThreadPoolExecutor构造函数中的第二个参数(maximumPoolSize=4
)是用来干什么的呢?我本来期望会创建4个线程,并且在执行结束后1分钟内会杀死其中的2个线程。