تمثل فئة ThreadLocal متغيرًا محليًا مؤشر ترابط. عن طريق وضع البيانات في ThreadLocal ، يمكن لكل مؤشر ترابط إنشاء نسخة من المتغير. يمكن أيضًا اعتبارها طريقة أخرى لمزامنة الخيط. من خلال إنشاء نسخة محلية مؤشر ترابط من متغير لكل مؤشر ترابط ، فإنه يتجنب التعارضات عندما تقرأ مؤشرات الترابط المتزامنة وتكتب نفس المورد المتغير في نفس الوقت.
الأمثلة على النحو التالي:
استيراد 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 classlocalt threadlocal <integer> value = new threadlocal <integer> () {private random random = new random () ؛ عدد صحيح متزامن محمي initialvalue () {retrand Random.NextInt (10000) ؛ }} ؛ زيادة الفراغ الثابتة العامة () {value.set (value.get () + 1) ؛ } static int get () {return value.get () ؛ }} static class accessor تنفذ RunNable {private Final int id ؛ accessor العامة (int id) {this.id = id ؛ } Override public void run () {بينما (! thread.currentThread (). isInterreded ()) {threadlocalvariableholder.increment () ؛ System.out.println (هذا) ؛ thread.yield () ؛ }} Override public string toString () {return "#" + id + ":" + threadlocalvariableholder.get () ؛ }} public static void main (string [] args) {executorService ExecutorService = Executors.NewCacheDthReadPool () ؛ لـ (int i = 0 ؛ i <5 ؛ i ++) {executeservice.execute (accessor (i)) ؛ } جرب {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. .
من نتائج التشغيل ، يمكننا أن نرى أن كل مؤشر ترابط يستخدم لمتغيراته المحلية الخاصة به ، ولا يتداخل كل قراءات ويكتب مع بعضها البعض.
يوفر ThreadLocal ثلاث طرق للعمل ، وتعيين ، والحصول عليه وإزالته.
في Android ، يتم استخدام ThreadLocal لإنشاء كائنات looper منفصلة لكل مؤشر ترابط.
الفئة النهائية العامة looper {private static final string tag = "looper" ؛ // sthreadlocal.get () سيعود فارغة إلا إذا كنت قد اتصلت بالإعداد (). Static Final Threadlocal <Oooper> sthreadlocal = new threadlocal <OOPER> () ؛ private static void تحضير (Quitallowed boolean) {if (sthreadlocal.get ()! = null) {throw new runTimeException ("يمكن إنشاء looper واحد فقط لكل مؤشر ترابط") ؛ } sthreadlocal.set (new looper (Quitallowed)) ؛ }. . . }عندما يحتاج مؤشر الترابط إلى قائمة انتظار الرسائل الخاصة به ، فإنه يتصل بـ looper.prepare () ، والذي سيقوم بإنشاء كائن looper و messagequeue ينتمي إلى مؤشر الترابط ، وحفظ كائن looper في ThreadLocal.