ThreadLocal简单测试

来源:互联网 发布:mac os x 10.13 镜像 编辑:程序博客网 时间:2024/05/16 07:05

ThreadLocal包装变量可以让每个执行的线程都拥有一份独立的引用,其中ThreadLocal使用键值对方式进行记录,key就是当前线程的名字。

详细介绍可以看:http://blog.csdn.net/lufeng20/article/details/24314381

下面写个小案例:

创建一个测试类,注入spring容器:

@Componentpublic class Work implements Serializable {    private int count = 0;    public void show() {        for (int i = 0; i < 5; i++) {            count++;            System.out.println("当前线程: " + Thread.currentThread().getName() + "  count: " + count);        }    }}

创建一个线程类,run方法就是执行上面的show方法(这里用ThreadLocal做了处理):

public class MyThread implements Runnable {    public void run() {        Work work = Main.threadLocal.get();        work.show();    }}

主测试类:

@Servicepublic class Main implements ApplicationContextAware {    public static ApplicationContext applicationContext = null;    public static ThreadLocal<Work> threadLocal = new ThreadLocal<Work>() {        @Override        protected Work initialValue() {            Work bean = applicationContext.getBean(Work.class);            return (Work) deepCopy(bean);        }    };    public static void main(String[] args) {        AbstractApplicationContext appContext = new ClassPathXmlApplicationContext("application07.xml");        Work work = appContext.getBean(Work.class);        ExecutorService executorService = Executors.newFixedThreadPool(10);        executorService.execute(new MyThread());        executorService.execute(new MyThread());        executorService.execute(new MyThread());        executorService.shutdown();        appContext.registerShutdownHook();    }    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {        this.applicationContext = applicationContext;    }    /**     * 深克隆     *     * @param src     * @return     */    public static Object deepCopy(Object src) {        ByteArrayOutputStream byteOut = null;        ObjectOutputStream out = null;        ByteArrayInputStream byteIn = null;        ObjectInputStream in = null;        Object dest = null;        try {            byteOut = new ByteArrayOutputStream();            out = new ObjectOutputStream(byteOut);            out.writeObject(src);            byteIn = new ByteArrayInputStream(byteOut.toByteArray());            in = new ObjectInputStream(byteIn);            dest = (Object) in.readObject();        } catch (Exception e) {            e.printStackTrace();        } finally {            try {                if (byteOut != null) {                    byteOut.close();                }                if (out != null) {                    out.close();                }                if (byteIn != null) {                    byteIn.close();                }                if (in != null) {                    in.close();                }            } catch (IOException e) {                // Auto-generated catch block                e.printStackTrace();            }        }        return dest;    }}

结果如下:

这里写图片描述

原创粉丝点击