首页 > 其他 > 详细

ThreadLocalDemo

时间:2019-03-05 10:39:24      阅读:205      评论:0      收藏:0      [点我收藏+]
package object;

class Msg {
    private String msg;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

class MsgConsumer {
    public void print() {
        System.out.println(Thread.currentThread().getName() + ",msg=" + MsgUtil.get().getMsg());
    }
}

class MsgUtil {
    public static Msg msg;
    // threadLocal线程同步,一个只能存一个,一次只能取一个
    private static ThreadLocal<Msg> threadLocal = new ThreadLocal<>();

    public static Msg get() {
        return threadLocal.get();
    }

    public static void set(Msg msg) {
        threadLocal.set(msg);
        // threadLocal.remove();
    }

}

/**
 * @author dayu
 */
public class ThreadLocalDemo {
    public static void main(String[] args) {
        new Thread(() -> {
            Msg msg = new Msg();
            msg.setMsg("aaaaaaaa");
            // MsgUtil.msg = msg;//使用该方法,会导致线程不同步
            MsgUtil.set(msg);//使用ThreadLocal同步数据
            new MsgConsumer().print();
        }, "user A").start();
        new Thread(() -> {
            Msg msg = new Msg();
            msg.setMsg("bbbbbbbb");
            // MsgUtil.msg = msg;
            MsgUtil.set(msg);
            new MsgConsumer().print();
        }, "user B").start();
    }

}

 

ThreadLocalDemo

原文:https://www.cnblogs.com/dayu007/p/10475070.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!