Use ThreadLocal to troubleshoot data sharing across multiple threads

Source: Internet
Author: User

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

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.