MainActivity例如以下:

package cc.cv;

import android.os.Bundle;
import android.app.Activity;
/**
* Demo描写叙述:
* ThreadLocal使用演示样例.
* 关于ThreadLocal的官方文档描写叙述
* Implements a thread-local storage, that is, a variable for which each thread has its own value.
* All threads share the same ThreadLocal object, but each sees a different value when accessing it,
* and changes made by one thread do not affect the other threads.
* The implementation supports null values.
* 该段文字描写叙述了ThreadLocal的用途:
* 1 对于同一个变量(即ThreadLocal中保存的变量)对于不同的线程其值是不同的.
* 2 全部线程共享一个ThreadLocal对象,可是訪问ThreadLocal对象中的变量时得到不同的值
* 3 某个线程改动了ThreadLocal对象中的变量值时不会影响到其它线程.
*
*
* 举个样例:
* 1 主线程中建立一个ThreadLocal对象(mThreadLocal)
* 2 在主线程中调用mThreadLocal的set()方法向mThreadLocal中保存一个字符串变量
* 3 在两个子线程中调用mThreadLocal的set()方法向mThreadLocal中保存一个字符串变量
* 4 在主线程中调用mThreadLocal的get()方法获取到mThreadLocal中为主线程保存字符串变量,发现其值未变.
*
*
* ThreadLocal的使用在Looper类中得到非常好的体现.保证了每一个线程和一个Looper一一相应,而且每一个Looper之间不受影响.
*
*/
public class MainActivity extends Activity {
private static ThreadLocal<String> mThreadLocal=new ThreadLocal<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
testThreadLocal();
}

private void testThreadLocal(){
//在主线程中调用ThreadLocal的set()方法保存一个变量
mThreadLocal.set("haha");
System.out.println("ThreadLocal保存的主线的变量值:"+mThreadLocal.get());


new Thread(){
public void run() {
//在第一个子线程中调用ThreadLocal的set()方法保存一个变量
mThreadLocal.set("xixi");
System.out.println("ThreadLocal保存的第一个子线程的变量值:"+mThreadLocal.get());
};
}.start();

new Thread(){
public void run() {
//在第二个子线程中调用ThreadLocal的set()方法保存一个变量
mThreadLocal.set("heihei");
System.out.println("ThreadLocal保存的第二个子线程的变量值:"+mThreadLocal.get());
};
}.start();


try {
Thread.sleep(1000*2);
//验证在第一个和第二个子线程对于ThreadLocal存储的变量值的改动没有影响到ThreadLocal存的主线程变量
System.out.println("ThreadLocal保存的主线的变量值:"+mThreadLocal.get());
} catch (Exception e) {

}
}


}


main.xml例如以下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

</RelativeLayout>