嘿,这是一个有趣的问题。我在我的Android项目中使用sqlite进行大量的sql操作。就此而言,我正在使用线程池来重用现有资源。线程池看起来像这样:
final int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
ThreadPoolExecutor threadPoolExecutor= new ThreadPoolExecutor(NUMBER_OF_CORES*2,NUMBER_OF_CORES*2,1L, TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(12,true),new PriorityThreadFactory(Process.THREAD_PRIORITY_BACKGROUND),new RejectedThread(context));
public class PriorityThreadFactory implements ThreadFactory {
private final int mThreadPriority;
public PriorityThreadFactory(int threadPriority) {
mThreadPriority = threadPriority;
}
@Override
public Thread newThread(final Runnable runnable) {
Runnable wrapperRunnable = new Runnable() {
@Override
public void run() {
try {
android.os.Process.setThreadPriority(mThreadPriority);
} catch (Throwable t) {
}
runnable.run();
}
};
return new Thread(wrapperRunnable);
}
}
public class RejectedThread implements RejectedExecutionHandler {
MyLogger myLogger;
public RejectedThread(Context context) {
this.myLogger=new MyLogger(RejectedThread.class.getSimpleName(), context);
}
@Override
public void rejectedExecution(Runnable worker, ThreadPoolExecutor executor) {
this.myLogger.info("Execution rejected for: "+worker.toString());
}
}
我还在为数据库中的每个CRUD(Create-Read-Update-Delete)操作创建一个新的Runnable(由上面的线程池执行)。下面是问题,除了sql操作的线程池之外,我还需要一个线程池来执行记录器操作,记录我所做的其余功能的系统行为。有没有办法防止任何压榨/(资源不足)因为我使用两个或更多线程池执行器(分开分配,在不同的目的使用和从不在另一个线程池执行器上执行线程池执行器)?
答案 0 :(得分:1)
我认为一般来说你的想法非常好,但你的实施效率有点低。
尝试自己回答这些问题:
根据我的经验,上述并发症都不是必需的。
例如,在我的所有应用程序中,我使用单个BackgroundThreadPoster
类实例,以便将工作卸载到后台线程。这堂课非常简单:
/**
* A single instance of this class should be used whenever we need to post anything to a (random) background thread.
*/
public class BackgroundThreadPoster {
ExecutorService mExecutorService = Executors.newCachedThreadPool();
public void post(Runnable runnable) {
mExecutorService.execute(runnable);
}
}
Executors.newCachedThreadPool()
返回的默认预配置实现就像魔术一样,我从未遇到任何定制其参数的需要。
可以在此处找到使用此方法的完整教程应用程序:https://github.com/techyourchance/android_mvc_tutorial
也许这对你也有用吗?