private static threadlocal<string> UuID = new Threadlocal<string> () {
Protected synchronized String InitialValue () {
return null;
}
};
public static String Getnextuuid () {
try {
if (uuid.get () = null)
return Uuid.get ();
Uuid.set (Uuidutil.replacestring (Uuidutil.getuuid (), "-", '-'));
return Uuid.get ();
} catch (Exception e) {
E.printstacktrace ();
}
return null;
}
Test thread
Package com.ushi.montor.test;
Import Com.ushi.montor.util.UUIDUtil;
public class TestClient extends Thread {
public void Run () {
for (int i = 0; i < 3; i++) {
System.out.println ("thread[" + thread.currentthread (). GetName () + "] sn[" + uuidutil.getnextuuid () + "]");
}
}
}
Test class
Package com.ushi.montor.test;
public class Testthreadlocal {
public static void Main (string[] args) {
3 threads share sn, each generating serial number
testclient T1 = new TestClient ();
TestClient t2 = new TestClient ();
testclient t3 = new TestClient ();
T1.start ();
T2.start ();
T3.start ();
}
}
Execution results
THREAD[THREAD-1] sn[6c9324d1b7774e2891179c57294b5e52]
THREAD[THREAD-1] sn[6c9324d1b7774e2891179c57294b5e52]
THREAD[THREAD-1] sn[6c9324d1b7774e2891179c57294b5e52]
THREAD[THREAD-0] sn[402526757d824d0988572b706dea7334]
THREAD[THREAD-0] sn[402526757d824d0988572b706dea7334]
THREAD[THREAD-0] sn[402526757d824d0988572b706dea7334]
Thread[thread-2] sn[1b10c4b83a43401da369c823cd1f7c2d]
Thread[thread-2] sn[1b10c4b83a43401da369c823cd1f7c2d]
Thread[thread-2] sn[1b10c4b83a43401da369c823cd1f7c2d]
Use ThreadLocal to troubleshoot data sharing across multiple threads