在Android中,哪个线程可运行传递给ScheduledExecutorService#schedule(Runnable command, long delay, TimeUnit unit)从Executors#newSingleThreadScheduledExecutor()返回的运行?
至于我的努力,我运行这段代码:
final ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.schedule(new Runnable() {
@Override
public void run() {
inflate.setBackgroundDrawable(background);
}
}, 200, TimeUnit.MILLISECONDS);
ses.shutdown();
on Moto G 2013,Android 5.0.2和setBackgroundDrawable操作正常,意味着它在主(UI)线程上运行。
具体来说,这适用于所有Android版本和设备吗?链接的javadoc页面没有说明它。我想避免陷阱,服务可能会产生一个新的单线程来运行操作。
答案 0 :(得分:1)
调用Thread
时,将创建新的ThreadGroup
(同一Executors.newSingleThreadScheduledExecutor()
)。隐式使用的DefaultThreadFactory
看起来像
static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
DefaultThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null)? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
如果你想重用UI-Thread,你应该编写自己的ThreadFactory
返回UI-Thread并调用Executors.newSingleThreadScheduledExecutor(yourNewlyCreatedThreadFactory)