Android: How to determine on which threads are my methods are running?
I would like to make sure that my methods are running on the threads that I supposed to be ran. For that, would like to add thread's name or id in my logs. In order to check if my methods are running in UIthread, thread1,thread2....threadx.
Problem:
- guide me on what I need to set to have the thread's name or id. I am not sure of this, if you have better approach,开发者_开发问答 please share to us on how to differentiate the UI threads to other additional running threads.
- guide me on how to log the above mentioned name or id. I have already the logging system. Just want to know the method need to call to obtain the name or id. Maybe, thread.name() or thread.id().
Any guidance is appreciated.
Use ThreadLocal. Actually example in docs exactly what you need:
import java.util.concurrent.atomic.AtomicInteger;
public class UniqueThreadIdGenerator {
private static final AtomicInteger uniqueId = new AtomicInteger(0);
private static final ThreadLocal < Integer > uniqueNum =
new ThreadLocal < Integer > () {
@Override protected Integer initialValue() {
return uniqueId.getAndIncrement();
}
};
public static int getCurrentThreadId() {
return uniqueId.get();
}
} // UniqueThreadIdGenerator
If you want, you can pass desired name to Thread and set it to static ThreadLocal
variable in the first line in run()
method.
精彩评论