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

为什么80%的码农都做不了架构师?>>>   hot3.png

private static ThreadLocal uuID = new ThreadLocal(){

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]


转载于:https://my.oschina.net/cpy/blog/486121

你可能感兴趣的:(使用 ThreadLocal 来解决多线程之间数据共享)