zoukankan      html  css  js  c++  java
  • java ThreadLocal的使用

    类ThreadLocal主要解决的就是每个线程绑定自己的值.

    package com.test;
    
    public class TestThreadLocal {
        
        public static ThreadLocal<String> t1 = new ThreadLocal<>();
        
        public void setLocalData(String value) {
            t1.set(value);
        }
        
        public void printLocalData() {
            System.out.println(Thread.currentThread().getName() + ":" + this.t1.get());
        }
        
        public static void main(String[] args) {
            TestThreadLocal local = new TestThreadLocal();
            Thread t1 = new Thread(new Runnable() {
                
                @Override
                public void run() {
                    local.setLocalData("testA");
                    local.printLocalData();
                }
            });
            Thread t2 = new Thread(new Runnable() {
                
                @Override
                public void run() {
                    local.printLocalData();
                }
            });
            t1.start();
            t2.start();
        }
    }
    结果:
    Thread-0:testA
    Thread-1:null
  • 相关阅读:
    浅谈Semaphore类
    Python浅谈requests三方库
    191104
    191103
    191102
    191101
    191031
    191030
    191029
    191028
  • 原文地址:https://www.cnblogs.com/gouge/p/9120405.html
Copyright © 2011-2022 走看看