java多线程--线程本地变量threadlocal

要解决什么问题?(业务场景)

是否依赖特殊底层代码?(代码层面)

主要的代码分层架构设计思路(代码层面)

public class Demo {
    public static void main(String[] args) {

        threadLocalIsSafe();
       // unSafe();
    }

    public static void threadLocalIsSafe(){
        for (int i = 0; i < 28; i++) {
            new Thread(()->{
                Massage msg = new Massage();
                msg.setInfo("线程:"+Thread.currentThread().getId());
                Channal.safeSetMsg(msg);
                Channal.unSafeSetMsg(msg);
                Channal.safeSend();
                Channal.unSafeSend();
            }).start();
        }

    }

    public static void unSafe(){
        for (int i = 0; i < 8; i++) {
            new Thread(()->{
                Massage msg = new Massage();
                msg.setInfo("线程:"+Thread.currentThread().getId());
                Channal.unSafeSetMsg(msg);
                Channal.unSafeSend();
            }).start();
        }
    }

}
class Channal{

    //线程本地变量
    public static ThreadLocal<Massage> threadLocal = new ThreadLocal<Massage>();
    public static void safeSetMsg(Massage m){
        threadLocal.set(m);
    }
    //取同一个线程(自身)
    public static void  safeSend(){
        System.err.println(Thread.currentThread().getId()+"[安全的消息发送]"+threadLocal.get().getInfo());
    }

    public static Massage msg;
    public static void unSafeSetMsg(Massage m){
        msg = m;
    }
    public static void unSafeSend(){
        System.err.println(Thread.currentThread().getId()+"[不安全的消息发送]"+msg.getInfo());
    }
}
class Massage{
    private String info;

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }
}

猜你喜欢

转载自blog.csdn.net/TianLiaoFeiJue/article/details/87986358