transmittablethreadlocalµÄ×÷ÓÃ
transmittablethreadlocal ÊÇÒ»ÖÖÓÃÓÚÔÚ¶àÏß³ÌÇéÐÎÖÐά»¤Ïֲ߳̾¿±äÁ¿µÄ²¢·¢¹¤¾ß£¬ËüµÄ×÷ÓðüÀ¨£º¿çÏß³Ìת´ïÊý¾Ý£»Î¬»¤Ïֲ߳̾¿ÇéÐΣ»¼ò»¯Ïß³ÌÇå¾²±à³Ì¡£
TransmittableThreadLocal µÄ×÷ÓÃ
TransmittableThreadLocal ÊÇÒ»ÖÖ²¢·¢±à³Ì¹¤¾ß£¬ÓÃÓÚÔÚ¶àÏß³ÌÇéÐÎÖÐά»¤Ïֲ߳̾¿±äÁ¿¡£Æä×÷ÓÃÊÇ£º
1. ¿çÏß³Ìת´ïÊý¾Ý
¹Å°å ThreadLocal ±äÁ¿Ö»ÔÚ½¨ÉèËüµÄÏß³ÌÖÐÓÐÓã¬ÎÞ·¨¿çÏß³Ìת´ï¡£¶ø TransmittableThreadLocal ±äÁ¿¿ÉÒÔͨ¹ýÏÔʽת´ïÀ´¿çÏ̹߳²Ïí¡£
2. ά»¤Ïֲ߳̾¿ÇéÐÎ
TransmittableThreadLocal ±äÁ¿¿ÉÒÔΪÿ¸öÏ߳̽¨ÉèºÍά»¤Ò»¸öµ¥¶ÀµÄÊý¾Ý¸±±¾£¬ÔÊÐíÏß³ÌÓµÓÐ×Ô¼ºµÄ˽ÓбäÁ¿ÜöÝÍ¡£ÕâÓë ThreadLocal ÏàËÆ£¬µ«ËüÌṩÁË¿çÏß³Ìת´ïÊý¾ÝµÄÌØÊ⹦Ч¡£
3. Simplifies thread-safe programming
TransmittableThreadLocal ¼ò»¯ÁËÏß³ÌÇå¾²µÄ±à³Ì¡£Í¨¹ýʹÓà TransmittableThreadLocal£¬¿ª·¢Ö°Ô±¿ÉÒÔÇáËɵØÔÚ²î±ðÏß³ÌÖ®¼ä¹²ÏíÊý¾Ý£¬¶øÎÞÐèµ£ÐIJ¢·¢»á¼ûºÍÊý¾ÝÒ»ÖÂÐÔµÄÎÊÌâ¡£
ÊÂÇéÔÀí
TransmittableThreadLocal ͨ¹ýÔÚÿ¸öÏß³ÌÖÐά»¤Ò»¸ö InheritableThreadLocal ±äÁ¿À´ÊÂÇé¡£µ±Ò»¸öÏ߳̽¨Éè TransmittableThreadLocal ¹¤¾ßʱ£¬Ëü½«½¨ÉèÒ»¸öÐ嵀 InheritableThreadLocal ±äÁ¿²¢ÓëÖ®¹ØÁª¡£
µ±Ïß³Ìת´ï TransmittableThreadLocal ¹¤¾ßʱ£¬InheritableThreadLocal ±äÁ¿Ò²»á±»×ª´ï£¬´Ó¶øÔÊÐí×ÓÏ̻߳á¼û¸¸Ï̵߳ÄÊý¾Ý¡£Ã¿¸ö×ÓÏ̶߳¼ÓÐ×Ô¼º InheritableThreadLocal µÄ¸±±¾£¬Òò´ËËüÃÇ¿ÉÒÔ×ÔÁ¦µØÐÞ¸ÄÊý¾Ý¡£
ʾÀý
ÒÔÏÂÊÇÒ»¸öʾÀý£¬Õ¹Ê¾ TransmittableThreadLocal µÄÓ÷¨£º
public class Main { private static TransmittableThreadLocal<integer> threadLocal = new TransmittableThreadLocal(); public static void main(String[] args) throws InterruptedException { // ½¨ÉèÏֲ߳̾¿±äÁ¿ threadLocal.set(10); // ½¨Éè×ÓÏß³Ì Thread thread = new Thread(() -> { // ×ÓÏ̻߳ñÈ¡Ïֲ߳̾¿±äÁ¿ int value = threadLocal.get(); // ÐÞ¸ÄÏֲ߳̾¿±äÁ¿ value++; threadLocal.set(value); }); thread.start(); thread.join(); // Ö÷Ï̻߳ñÈ¡Ïֲ߳̾¿±äÁ¿ int value = threadLocal.get(); // Êä³öÏֲ߳̾¿±äÁ¿ System.out.println("Main thread value: " + value); } }</integer>
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öʾÀýÖУ¬Ö÷Ï߳̽¨ÉèÁËÒ»¸ö TransmittableThreadLocal ±äÁ¿²¢ÉèÖÃÆäֵΪ 10¡£È»ºóËü½¨ÉèÒ»¸ö×ÓỊ̈߳¬×ÓÏ߳̿ÉÒÔ»á¼ûºÍÐÞ¸ÄÖ÷Ïß³ÌµÄ TransmittableThreadLocal ±äÁ¿¡£Êä³ö½«ÏÔʾ×ÓÏß³ÌÐ޸ĺóµÄÖµ£¬ÕâÅú×¢Êý¾ÝÒÑ¿çÏß³ÌÀÖ³Éת´ï¡£
ÒÔÉϾÍÊÇtransmittablethreadlocalµÄ×÷ÓõÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡