Android sdk允许使用以下内容自定义非ui线程的堆栈大小:
ThreadGroup group = new ThreadGroup("threadGroup");
new Thread(group, runnableObject, "YourThreadName", 20000).start();
是否可以进行类似的调用,允许我使用堆栈大小增加的AsyncTask
api?
答案 0 :(得分:2)
AsyncTask
有一个ThreadFactory
的私有静态对象(匿名内部类)来生成新的Thread
[1]:
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
正如您所看到的,newThread
方法返回Thread(Runnable runnable, String threadName)
而没有stackSize
的任何参数。所以你无法改变它。但是,线程中的堆栈大小具有高度依赖于平台的解释。甚至可以完全忽略它[2]。
修改您可以使用自定义执行者,而不是THREAD_POOL_EXECUTOR
使用AsyncTask
的{{1}}。例如:
sThreadFactory
然后,您可以使用自定义执行程序:
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE = 1;
private static final ThreadFactory yourFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
ThreadGroup group = new ThreadGroup("threadGroup");
return new Thread(group, r, "YourThreadName", 20000);
}
};
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
public static final Executor YOUR_CUSTOM_THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, yourFactory);
[1] https://github.com/android/platform_frameworks_base/blob/master/core/java/android/os/AsyncTask.java
[2] http://developer.android.com/reference/java/lang/Thread.html
答案 1 :(得分:0)
所有AsyncTasks都由共享(静态)ThreadPoolExecutor和LinkedBlockingQueue在内部控制。当您在AsyncTask上调用execute时,ThreadPoolExecutor将通过在内部运行新线程或对其进行排队来执行它。因此线程堆栈大小由内部ThreadPoolExecutor控制。您无法访问它。如果要控制堆栈大小,请使用您自己的ThreadPoolExecutor。但是,正如@ yaa110所述,堆栈大小参数与平台高度相关。