Java 中ThreadLocal類詳解
ThreadLocal類,代表一個線程局部變量,通過把數(shù)據(jù)放在ThreadLocal中,可以讓每個線程創(chuàng)建一個該變量的副本。也可以看成是線程同步的另一種方式吧,通過為每個線程創(chuàng)建一個變量的線程本地副本,從而避免并發(fā)線程同時讀寫同一個變量資源時的沖突。
示例如下:
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();
}
}
運行結(jié)果:
#1: 9685 #1: 9686 #2: 138 #2: 139 #2: 140 #2: 141 #0: 5255 。。。
由運行結(jié)果可知,各線程都用于各自的Local變量,并各自讀寫互不干擾。
ThreadLocal共提供了三個方法來操作,set,get和remove。
在Android 中的Looper,即使用了ThreadLocal來為每個線程都創(chuàng)建各自獨立的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));
}
。。。
}
當(dāng)某個線程需要自己的Looper及消息隊列時,就調(diào)用Looper.prepare(),它會為線程創(chuàng)建屬于線程的Looper對象及MessageQueue,并將Looper對象保存在ThreadLocal中。
相關(guān)文章
Spring之動態(tài)注冊bean的實現(xiàn)方法
這篇文章主要介紹了Spring之動態(tài)注冊bean的實現(xiàn)方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08
Java中的HashSet詳解和使用示例_動力節(jié)點Java學(xué)院整理
HashSet 是一個沒有重復(fù)元素的集合。接下來通過實例代碼給大家介紹java中的hashset相關(guān)知識,感興趣的朋友一起看看吧2017-05-05
Java中的==和equals()區(qū)別小結(jié)
在Java編程中,理解==操作符和equals()方法的區(qū)別是至關(guān)重要的,本文主要介紹了Java中的==和equals()區(qū)別,具有一定的參考價值,感興趣的可以了解一下2023-08-08

