在Java/Android中,有没有办法检查当前正在执行的代码行是否在后台线程上执行?
我想出了一个小程序,它终于达到了意大利面条式的阶段……这是故意的,你看,因为这样……如果竞争对手拿到了代码,并且他们“打开引擎盖”,看着它超过 20 秒后,他们的头发会着火,他们会尖叫着逃跑......但现在连我都感到困惑,我需要以某种方式检查这种情况。
图表-A:
// can be called from 1,067 places... some of which are background threads.
public void startDoingAFunDance(String caller, int wobbleIntensity, int spineAngle, int feetSeparationInInches) {
if (!validCallersForFunDance.contains(caller)) {
Log.i("XXX", "Caller not allowed.");
return;
}
boolean wasCalledFromBackgroundThread = // ? < what to put here > ?
Log.i("XXX", "Was startDoingAFunDance() called from a background thread? And the answer is: " + wasCalledFromBackgroundThread);
// classified
}
最佳答案
一个简单的方法可能是下面这样
boolean wasCalledFromBackgroundThread = (Thread.currentThread().getId() != 1);
后台线程没有 id 1(UI 线程有)。
关于java - 如何检查代码是否在后台运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51692158/