Java Threadlocal class Detailed _java

Source: Internet
Author: User
Tags prepare static class

The Threadlocal class, which represents a thread-local variable, lets each thread create a copy of the variable by placing the data in the threadlocal. It can also be viewed as another way of threading synchronization by creating a thread-local copy of a variable for each thread, thereby avoiding conflicts when concurrent threads read and write to the same variable resource at the same time.

Examples are as follows:

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 ();

 }

}

Run Result:

#1:9685
#1:9686
#2:138
#2:139 #2:140 #2: #0:
5255
...

From the results of the operation, each thread is used for its own local variables, and read and write each other.

Threadlocal provides a total of three methods to operate, Set,get and remove.

In Android, Looper uses threadlocal to create separate Looper objects for each thread.

Public final class Looper {
 private static final String TAG = "Looper";

 Sthreadlocal.get () would return null unless for 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 could created per thread");
  }
  Sthreadlocal.set (New Looper (quitallowed));
}

When a thread needs its own looper and message queues, it calls Looper.prepare (), which creates the Looper object and MessageQueue for the thread that belong to the thread, and saves the Looper object in Threadlocal.

Related Article

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.