码迷,mamicode.com
首页 > 编程语言 > 详细

使用 ThreadLocal 来解决多线程之间数据共享

时间:2015-07-31 16:32:20      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

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;

}

//测试线程

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() + "]");

}

}

}

//测试类

package com.ushi.montor.test;

 

public class TestThreadLocal {

public static void main(String[] args) {

        //  3个线程共享sn,各自产生序列号

        TestClient t1 = new TestClient();

        TestClient t2 = new TestClient();

        TestClient t3 = new TestClient();

        t1.start();

        t2.start();

        t3.start();

}

}

 

//执行结果

 

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]


使用 ThreadLocal 来解决多线程之间数据共享

标签:

原文地址:http://my.oschina.net/cpy/blog/486121

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!