Thread local Variables for Java concurrent programming

Source: Internet
Author: User

sharing data is one of the most central issues in concurrent programs, and is especially important for inheriting the thread class or implementing an Runnable interface object.

If you create an object that implements an instance of the Runnable interface's class, uses it as an incoming parameter, creates multiple thread objects, and starts these threads, all threads share the same properties. If you change a property in one thread, all threads are affected by this change.

In some cases, the properties of this object do not need to be shared by all threads. Java provides a good mechanism for threading local variables (thread-local Variable).

We write a simple demo, one with the problem just mentioned, and another using the thread local variable mechanism to solve the problem.

1. Create a class of Class Unsafetask, which implements the Runnable interface. And declare a Java.util.Date property.

public class Unsafetask implements runnable{
Private Date StartDate; }

2. Implement the Run () method. This method initializes the StartDate property and prints the value to the console. Let the thread hibernate for a random time, and then print the value again to the console.

Public void Run () {
startdate=new Date ();
System.out.printf ("Starting thread:%s:%s \ n", Thread.CurrentThread (). GetId (), startdate);
try{
TimeUnit.SECONDS.sleep ((int) math.rint (math.random () *10));
}catch (interruptedexception e) {
e.printstacktrace ();
          }
System.out.printf ("Thread finished:%s:%s\n", Thread.CurrentThread (). GetId (), startdate);
       }

3. A main main class is created and contains a main () method. This method creates a Unsafetask class object that uses it as an incoming parameter to create 10 thread objects and start 10 threads, each with a thread start interval of 2 seconds.

Public class Main {
Public static void Main (string[] args) {
unsafetask task=new unsafetask ();
for (int i=0;i<10;i++) {
thread thread=new thread (task);
Thread.Start ();
try{
TimeUnit.SECONDS.sleep (2);
}catch (interruptedexception e) {
e.printstacktrace ();
                
             }
         }
     }
}

4. Running Results

Each thread has a different start time. When they end, three threads have the same StartDate property value.

5. Next we use the thread local variable mechanism to solve the above problem.

6. Create a Safetask class to implement the Runnable interface.

public class Safetask implements runnable{}

7. Declare a Threadlocal<date> object. This object is implicitly implemented in the InitialValue () method, returning the current date.

private static threadlocal<date> startdate=new threadlocal<date> () {
Protected Date Initalvalue () {
return new Date ();
}
};

8. Implement the Run () method. The same functionality as the above method, but the StartDate property has changed.

Public void Run () {
System.out.printf ("Starting Thread:%s:%s\n", Thread.CurrentThread (). GetId (), Startdate.get ());
try {
TimeUnit.SECONDS.sleep ((int) math.rint (math.random () *10));
} catch (Interruptedexception e) {
e.printstacktrace ();
          }
          
System.out.printf ("Thread finished:%s:%s\n", Thread.CurrentThread (). GetId (), Startdate.get ());
      }

9.Main is the same as the Runnable class object that was created and passed in as a parameter.

Public class Main {
Public static void Main (string[] args) {
safetask task=new safetask ();
for (int i=0;i<3;i++) {
thread thread=new thread (task);
        
try{
TimeUnit.SECONDS.sleep (2);
}catch (interruptedexception e) {
e.printstacktrace ();
                
             }
Thread.Start ();
         }
     }
}

10. Run the results.

Thread local Variables for Java concurrent programming

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.