1. 程式人生 > >ThreadLocal使用演示樣例

ThreadLocal使用演示樣例

log creat imp apk nts eight get() 演示 extend

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>


ThreadLocal使用演示樣例