La classe ThreadLocal représente une variable locale de thread. En plaçant les données dans ThreadLocal, chaque thread peut créer une copie de la variable. Il peut également être considéré comme un autre moyen de synchronisation du fil. En créant une copie de thread-locale d'une variable pour chaque thread, il évite les conflits lorsque des threads simultanés lisent et écrivent la même ressource variable en même temps.
Les exemples sont les suivants:
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 (); entier synchronisé protégé initialValue () {return random.nextint (10000); }}; public static void incment () {value.set (value.get () + 1); } public static int get () {return value.get (); }} Accessor de classe statique implémente Runnable {private final int id; Accessor public (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) {EMIRGETORSERVICE EMMIRESSERVICE = EMIRESS.NEWCACHEDTHREADPOOL (); pour (int i = 0; i <5; i ++) {eeccuteService.ExECUTE (nouvel accessor (i)); } essayez {timeunit.microseconds.Sleep (1); } catch (InterruptedException e) {e.printStackTrace (); } EMMICRORSERVICE.SHUTDOWNNOW (); }}Résultats en cours:
# 1: 9685 # 1: 9686 # 2: 138 # 2: 139 # 2: 140 # 2: 141 # 0: 5255.. .
D'après les résultats en cours d'exécution, nous pouvons voir que chaque fil est utilisé pour ses propres variables locales, et chaque lecture et écriture n'interfère pas entre elles.
ThreadLocal fournit trois méthodes pour fonctionner, définir, obtenir et supprimer.
Dans Android, ThreadLocal est utilisé pour créer des objets Looper séparés pour chaque thread.
public final class Looper {private static final string tag = "looper"; // sthReadLocal.get () retournera null à moins que vous n'ayez appelé préparez (). statique final threadLocal <Looper> sthReadlocal = new ThreadLocal <Looper> (); Private static void prépare (booléen quitallowed) {if (sthreadlocal.get ()! = null) {lancez new RuntimeException ("un seul looper peut être créé par thread"); } sthReadLocal.set (new Looper (quitallowed)); }. . . }Lorsqu'un thread a besoin de sa propre file d'attente LOOPER et de message, il appelle Looper.Prepare (), qui créera un objet Looper et MessageQueue appartenant au thread pour le thread, et enregistrera l'objet Looper dans ThreadLocal.