首页 > 编程语言 > 详细

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

时间:2015-07-31 16:32:14      阅读:357      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!