ThreadLocal共享变量2_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > ThreadLocal共享变量2

ThreadLocal共享变量2

 2018/1/5 19:16:17  firkeuuuu  程序员俱乐部  我要评论(0)
  • 摘要:importjava.util.Random;publicclassThreadLocalTest{privatestaticThreadLocal<Integer>x=newThreadLocal();publicstaticvoidmain(String[]args){for(inti=0;i<2;i++){newThread(newRunnable(){@Overridepublicvoidrun(){intdata=newRandom().nextInt()
  • 标签:thread
class="java" name="code">import java.util.Random;

public class ThreadLocalTest {
    private static ThreadLocal<Integer> x = new ThreadLocal();

    public static void main(String[] args) {
        for (int i = 0; i < 2; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int data = new Random().nextInt();
                    System.out.println(Thread.currentThread().getName() + ":" + data);
                    MyThreadScopeData.getInstance().setName(data+"");
                    MyThreadScopeData.getInstance().setAge(data);
                    new A().get();
                    new B().get();

                }
            }).start();
        }
    }

    static class A{
        public void get(){
            System.out.println(Thread.currentThread().getName() + ":" + MyThreadScopeData.getInstance().getName() + " " + MyThreadScopeData.getInstance().getAge());
        }
    }
    static class B{
        public void get(){
            System.out.println(Thread.currentThread().getName() + ":" + MyThreadScopeData.getInstance().getName() + " " +  MyThreadScopeData.getInstance().getAge());
        }
    }
}

class MyThreadScopeData{
    private String name;
    private int age;
    private MyThreadScopeData(){

    }
    public static MyThreadScopeData getInstance(){
        MyThreadScopeData instance= map.get();
        if(instance == null){
            instance = new MyThreadScopeData();
            map.set(instance);
        }
        return instance;
    }
    private static ThreadLocal<MyThreadScopeData> map = new ThreadLocal<>();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

?

发表评论
用户名: 匿名