Multi-thread ing tool-local thread value and local multi-thread ing thread

Source: Internet
Author: User

Multi-thread ing tool-local thread value and local multi-thread ing thread

ThreadLocal is equivalent to a Map <Thread, T>. Each Thread uses its own Thread object Thread. currentThread () is used as the key to access data, but ThreadLocal is actually a packaged Map, and the thread can only access its own data, and cannot operate on the data of other threads.

  • T get ()
  • Set (T)
  • Remove ()

Sample Code:

Public static void main (String [] args) {String [] names = new String [] {"A", "B", "C", "D ", "E"}; for (int I = 0; I <names. length; I ++) {final String myName = names [I]; new Thread () {public void run () {name. set (myName); try {Thread. sleep (500);} catch (InterruptedException e) {e. printStackTrace () ;}test ();}}. start ();}/* running result: thread-0-> my name is A Thread-2-> my name is C Thread-1-> my name is B Thread-3-> my name is D thread-4-> my name is E */} private static ThreadLocal <String> name = new ThreadLocal <String> (); public static void test () {System. out. println (Thread. currentThread (). getName () + "-> my name is" + name. get ());}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.