从ThreadLocal实际应用实例了解ThreadLocal

ThreadLocal是个啥?

首先,官方的解释叫做:线程本地变量。这个解释给绝大部分人都是一头雾水。现在我用尽可能直白的语言来解释一下。ThreadLocal是Thread的属性threadlocals的管理工具,就是将一个变量拷贝给每个线程一份,每个线程对这个变量的操作是彼此独立的,不会相互影响。而threadlocals的底层则是一个ThreadLocalMap,这个Map的底层key值是ThreadLocal的虚引用,而Value则是实际的每个线程的所要使用的变量值。

案例一:

两个线程不适用ThreadLocal对同一个数据进行操作:

package server;
public class forLearning2 { 
    private static ThreadLocal<Integer> local = new ThreadLocal<>(); 
    public void setNum(int data){ 
        local.set(data); 
    } 
    public int getNum(){ 
        return local.get(); 
    } 
    public static void main(String[] args){ 
        forLearning2 flag = new forLearning2(); 
        //System.out.println(flag.getNum()); 
        new MyThread("线程一",flag).start(); 
        new MyThread("线程二",flag).start();
        }
}
class MyThread extends Thread{ 
    private forLearning2 data; 
    public MyThread(String name, forLearning2 data){ 
        super(name); 
        this.data=data; 
    } 
    @Override 
    public void run(){ 
        data.setNum(10); 
        int num = data.getNum();
        while (num!=0){ 
            System.out.println(this.getName()+num--); 
        } 
    }
}

案例二:

两个线程用ThreadLocal对同一个变量进行操作:

package server;
public class forLearning2 { 
    private static final ThreadLocal<Integer> local = new ThreadLocal<>(); 
    public void setNum(int data){ 
        local.set(data); 
    } 
    public int getNum(){ 
        return local.get(); 
    } 
    public static void main(String[] args){ 
        forLearning2 flag = new forLearning2(); 
        //System.out.println(flag.getNum()); 
        new MyThread("线程一",flag).start(); 
        new MyThread("线程二",flag).start(); 
        local.remove(); 
    }
}
class MyThread extends Thread{ 
    private final forLearning2 data; 
    public MyThread(String name, forLearning2 data){ 
        super(name); 
        this.data=data; 
    } 
    @Override public void run(){ 
        data.setNum(10); 
        int num = data.getNum(); 
        while (num!=0){ 
        System.out.println(this.getName()+num—); 
        } 
    }
}

你可能感兴趣的:(JAVA,数据结构)