Java 中ThreadLocal類詳解。本站提示廣大學習愛好者:(Java 中ThreadLocal類詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是Java 中ThreadLocal類詳解正文
ThreadLocal類,代表一個線程部分變量,經由過程把數據放在ThreadLocal中,可讓每一個線程創立一個該變量的正本。也能夠算作是線程同步的另外一種方法吧,經由過程為每一個線程創立一個變量的線程當地正本,從而防止並發線程同時讀寫統一個變量資本時的抵觸。
示例以下:
import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import com.sun.javafx.webkit.Accessor; public class ThreadLocalTest { static class ThreadLocalVariableHolder { private static ThreadLocal<Integer> value = new ThreadLocal<Integer>() { private Random random = new Random(); protected synchronized Integer initialValue() { return random.nextInt(10000); } }; public static void increment() { value.set(value.get() + 1); } public static int get() { return value.get(); } } static class Accessor implements Runnable{ private final int id; public Accessor(int id) { this.id = id; } @Override public void run() { while (!Thread.currentThread().isInterrupted()) { ThreadLocalVariableHolder.increment(); System.out.println(this); Thread.yield(); } } @Override public String toString() { return "#" + id + ": " + ThreadLocalVariableHolder.get(); } } public static void main(String[] args) { ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i < 5; i++) { executorService.execute(new Accessor(i)); } try { TimeUnit.MICROSECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } executorService.shutdownNow(); } }
運轉成果:
#1: 9685 #1: 9686 #2: 138 #2: 139 #2: 140 #2: 141 #0: 5255 。。。
由運轉成果可知,各線程都用於各自的Local變量,並各自讀寫互不攪擾。
ThreadLocal共供給了三個辦法來操作,set,get和remove。
在Android 中的Looper,即便用了ThreadLocal來為每一個線程都創立各自自力的Looper對象。
public final class Looper { private static final String TAG = "Looper"; // sThreadLocal.get() will return null unless you've called prepare(). static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>(); private static void prepare(boolean quitAllowed) { if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(quitAllowed)); } 。。。 }
當某個線程須要本身的Looper及新聞隊列時,就挪用Looper.prepare(),它會為線程創立屬於線程的Looper對象及MessageQueue,並將Looper對象保留在ThreadLocal中。