我正在尝试了解 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 个线程,其中 2 个线程在执行结束 1 分钟后被杀死