最近在项目中使用到了JDK提供的线程池,遇到了在多线程环境下在线程内部共享数据的问题
使用ThreadLocal 来解决线程内部共享数据的问题
定义BO
package com.unicom.ucloud.aar.kettle.bo; import com.unicom.ucloud.aar.kettle.vo.KettleRunMessageVo; /** * @author jiaoyiping@gmail.com * @remark */ public class ThreadLocalMessage { private ThreadLocal<KettleRunMessageVo> messages; private ThreadLocalMessage(){ messages = new ThreadLocal<KettleRunMessageVo>(); } public KettleRunMessageVo getMessage() { return messages.get(); } public void setMessage(KettleRunMessageVo message) { messages.set(message); } private static ThreadLocalMessage threadLocalMessage = new ThreadLocalMessage(); public static ThreadLocalMessage getInstance(){ return threadLocalMessage; } }
//在线程中使用
KettleRunMessageVo message = ThreadLocalMessage.getInstance().getMessage(); if(message==null) { message = new KettleRunMessageVo(); ThreadLocalMessage.getInstance().setMessage(message); }
使用message的set方法设置相应的值
在同一个线程中的其他地方get这个message 得到相应的值