标签:uncaught sdn out tin class 之间 todo creat string
线程局部变量。
在非主线程中直接new Handler() 会报如下的错误: E/AndroidRuntime( 6173): Uncaught handler: thread Thread-8 exiting due to uncaught exception E/AndroidRuntime( 6173): java.lang.RuntimeException: Can‘t create handler inside thread that has not called Looper.prepare() 原因是非主线程中默认没有创建Looper对象,需要先调用Looper.prepare()启用Looper。
举例:
package test; import test.*; public class Test { static final ThreadLocal<ThreadValue> mThreadLocal = new ThreadLocal<ThreadValue>(); /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ThreadValue threadValue = new ThreadValue("主线程"); mThreadLocal.set(threadValue); System.out.print("in main thread : mThreadLocal:" + mThreadLocal +"\n"); System.out.print("in main thread : 名字:" + mThreadLocal.get().name +"\n"); mThreadLocal.get().print(); new Thread(new Runnable() { @Override public void run() { ThreadValue childThreadValue = new ThreadValue("子线程"); mThreadLocal.set(childThreadValue); System.out.print("in child thread : mThreadLocal:" + mThreadLocal +"\n"); System.out.print("in child thread : 名字:" + mThreadLocal.get().name +"\n"); mThreadLocal.get().print(); } }).start(); } } package test; public class ThreadValue { String name; public ThreadValue() { } public ThreadValue(String name) { this.name=name; } public void print() { System.out.print("this = " + this+" \n"); } }
结果:
然后编译:javac test/*.java 运行:java test.Test 输出: in main thread : mThreadLocal:java.lang.ThreadLocal@788bf135 in main thread : 名字:主线程 this = test.ThreadValue@2b890c67 in child thread : mThreadLocal:java.lang.ThreadLocal@788bf135 in child thread : 名字:子线程 this = test.ThreadValue@4f93b604
可以看出由于mThreadLocal定义为静态最终变量,所以在主线程和子线程中,mThreadLocal都是同一个实例。
但是在两个线程中调用mThreadLocal.get(),得到的ThreadValue对象却并不相同。
这是因为mThreadLocal.get(),取到的对象是线程内的局部变量,相互之间并不干扰。
---------------------
作者:??-D-Luffy
来源:CSDN
原文:https://blog.csdn.net/zyfzhangyafei/article/details/64927617
版权声明:本文为博主原创文章,转载请附上博文链接!
标签:uncaught sdn out tin class 之间 todo creat string
原文地址:https://www.cnblogs.com/Jackie-zhang/p/9895505.html