在前面讲关于Handler的Looper的时候,我们讲到过Looper的获取和设置,是通过ThreadLocal来操作的,如下:
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
在准备Looper的时候,
public static void prepare() {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper());
}
在获取Looper的时候,
/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static Looper myLooper() {
return sThreadLocal.get();
}
那么ThreadLocal的作用到底什么呢?为什么会有ThreadLocal的出现呢?
首先,我们先来看下面一个例子吧,如下:
public class HelperTesting {
private String text = "empty";
private static HelperTesting helperTesting = new HelperTesting();
private void printText() {
System.out.println(text);
}
private void changeText(String str) {
text = str;
}
private void printWithLine(String str){
System.out.println("##################### " + str +" #############################");
}
public static void main(String[] args) {
helperTesting.printWithLine(Thread.currentThread().getName() + " start");
helperTesting.printText();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
helperTesting.printWithLine(Thread.currentThread().getName() + " start");