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