通常,您应该在一个接口下包装自己的执行器。
public interface Scheduler {
void runOnThread(Runnable runnable);
}
/**
* A Scheduler implementation based on ModernAsyncTask with an unbounded task queue.
**/
public class IoScheduler implements Scheduler {
private static final int CORE_POOL_SIZE = 5;
private static final int MAXIMUM_POOL_SIZE = 128;
private static final int KEEP_ALIVE = 1;
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "IoScheduler #" + mCount.getAndIncrement());
}
};
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>();
/**
* An {@link Executor} that can be used to execute tasks in parallel.
*/
private static final Executor THREAD_POOL_EXECUTOR =
new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
@Override
public void runOnThread(Runnable runnable) {
THREAD_POOL_EXECUTOR.execute(runnable);
}
}
你通常会用匕首:
@Singleton
public class IoScheduler implements Scheduler {
@Inject
IoScheduler() {}
...
}
@Module
public class SchedulerModule {
public static final String BACKGROUND = "BACKGROUND";
@Named(BACKGROUND) // you can also use @Qualifier
@Provides
Scheduler ioScheduler(IoScheduler ioScheduler) {
return ioScheduler;
}
}
然后在其他地方使用
@Singleton
public class MyService {
private final Scheduler ioScheduler;
@Inject
MyService(@Named(SchedulerModule.BACKGROUND) Scheduler ioScheduler) { // you can use @Qualifier here instead of @Named
this.ioScheduler = ioScheduler;
}
....
}
(尽管如此
ioScheduler
更适合读:对于写操作,您可能需要考虑一个单独的单线程执行器。)
所以如果你读到它的结尾,它实际上是这样的方法:
2.)谷歌向日葵样本使用
runOnIoThread
哪种方法可以
IO_EXECUTOR.execute(job)
哪里
IO_EXECUTOR = Executors.newSingleThreadExecutor