Java concurrent programming--thread local variable usage

Source: Internet
Author: User

Sharing data is one of the core problems of concurrent programs. Let's look at a deom and feel the impact of multithreading on attributes.

Code:

Unsafetask.java

Package Com.tgb.klx.thread;import Java.text.simpledateformat;import Java.util.date;import Java.util.concurrent.timeunit;public class Unsafetask implements Runnable {private String startdate; @Overridepublic void Run () {SimpleDateFormat sdf=new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Startdate=sdf.format (new  Date ()); System.out.println ("Start Thread:" +thread.currentthread (). GetId () + ", Start time:" +startdate); try {TimeUnit.SECONDS.sleep (int ) Math.rint (Math.random () *10));} catch (Interruptedexception e) {e.printstacktrace ();} SYSTEM.OUT.PRINTLN ("End Thread:" +thread.currentthread (). GetId () + ", Start time:" +startdate);}}

Core.java

Package Com.tgb.klx.thread;import Java.util.concurrent.timeunit;public class Core {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 ();}}}}


Operation Result:


As you can see, the time that the last thread started is the time the remaining threads end, and the apparent time that one thread started was modified by another thread.



So, how can we guarantee that a thread's local variables will not be modified by other threads? Below we use threadlocal to protect the properties of the phase thread from being modified by other threads:

Code:

Safetask.java

Package Com.tgb.klx.thread;import Java.text.simpledateformat;import Java.util.date;import Java.util.concurrent.timeunit;public class Safetask implements Runnable {private static threadlocal<string> Startdate=new threadlocal<string> () {protected String InitialValue () {SimpleDateFormat sdf=new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); return Sdf.format (New  Date ());}}; @Overridepublic void Run () {System.out.println ("Start Thread:" +thread.currentthread (). GetId () + ", Start Time:" +startdate.get ()); try {TimeUnit.SECONDS.sleep (int) math.rint (math.random () *10)} catch (Interruptedexception e) {e.printstacktrace () ;} SYSTEM.OUT.PRINTLN ("End Thread:" +thread.currentthread (). GetId () + ", Start Time:" +startdate.get ());}}

Operation Result:

We guarantee the security of the local variables within the thread. ThreadLocal is a version of JDK 1.2 that provides a new way to solve the concurrency problem of multi-threaded java.lang.threadlocal,threadlocal. Using this tool class can be very concise to write a graceful multithreaded program, threadlocal is not a thread, but the local variable thread.


Java concurrent programming--thread local variable usage

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.