我基本上是想了解我的代码在哪些线程上运行。 理论上,它应该全部在前台组中运行,因为代码位于在前台启动的服务内部。 假设我有以下课程:
public class Test {
private Runnable runnable;
private final Handler handler;
public Test()
{
this.random = new Random();
this.handler = new Handler();
}
private Runnable getRunnable(final String gpsCoordinates)
{
return new Runnable() {
@Override
public void run() {
System.out.println("Current Thread Test: "+Thread.currentThread().getName());
System.out.println("Current Looper Test: "+ Looper.myLooper());
handler.postDelayed(this, INTERVAL_MILLIS);
if(condition)
handler.removeCallbacks(runnable);
}
};
}
public void test(final String gpsCoordinates)
{
runnable = getRunnable(gpsCoordinates);
handler.postDelayed(runnable, DELAY_MILLIS);
}
}
public class FooThread extends Thread {
private Test test;
...
public FooThread(Test test)
{
this.test = test;
}
@Override
public void run()
{
test.test();
//other stuff
System.out.println("Current Thread FooThread: "+Thread.currentThread().getName());
System.out.println("Current Looper FooThread: "+ Looper.myLooper());
}
}
正如你所看到的,我有一个 Test 类,它以一定的时间间隔执行一些代码,直到满足条件,还有一个 FooThread 类,它调用 Test.test 而不是做其他事情。
在我的服务中,我只需运行:
new FooThread(new Test()).start();
令我惊讶的是,这就是我得到的:
Current Thread FooThread: Thread-3
Current Looper FooThread: null
Current Thread Test: main
Current Looper Test: Looper (main, tid 2) {3c367e9}
有人可以向我解释为什么 test.test() 位于主线程上,因为它的代码位于可运行的内部吗? 另外,我可以检查Thread-3确实是前台组中的线程而不是后台组中的线程?通常,前台组中的线程从设备获得大约 95% 的总执行时间,而后台组大约获得 5%。 谢谢你。
有人可以向我解释为什么 test.test() 位于主线程上,因为它的代码位于可运行的内部吗?
因为那是你初始化它的地方。
你说:
> 在我的服务中,我只需运行: new FooThread(new Test()).start();
所以...
new Test()
,它是在主线程上创建的。Test
构造函数创建new Handler()
,它又是在主线程上创建的。start()
Thread
,它会产生Thread-3
Thread-3
向 Handler()
发送一条延迟消息,该消息将在创建它的主线程上运行。Thread
可运行打印它位于它生成的Thread-3
线程上。处理程序使用
Runnable
的事实是无关紧要的。 Runnable
只是“可以运行的东西”的接口 - 它不有 是线程。 A Thread
是 Runnable
- Runnable
不是 Thread
。
另外,我可以检查Thread-3确实是前台组中的线程而不是后台组中的线程?
这是问题还是评论?是的,您可以获得线程优先级。