当前位置:   article > 正文

JAVA多线程变量的深入认识(三)_java thread 独立变量

java thread 独立变量

现在的问题来了,当我们关注例子I,希望共享类RunInstance,即
    RunInstance t = new RunInstance();
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);
却又要对变量进行线程单独化的管理时,怎么办?这时候就有了ThreadLocal。请看
例子III
首先我们对类TestInstance做一下改造,也就是把Flag变成ThreadLocal,即线程的独自变量
改造如下1,2,3点,接着我们仍旧运行例子I
class TestInstance {
    static Integer count = 0;
    //1: public int flag = 0;
    public ThreadLocal flag = new ThreadLocal(){
        public Integer initialValue(){
            return 0;
        }
    };

    public void runtest(){
    //2:  if (flag ==0)m1();  
        if (flag.get() ==0)m1();  
        else   m2();
        }
    public  void m1(){
    //3.  flag=1;
        flag.set(1);
        synchronized(count){
        for(int i = 0;i < 10; i++){
            count++;   
            System.out.println(Thread.currentThread().getName()+": m1's printing : count = "+count);  
            }
        }
    }
    public void m2(){
        synchronized(count){    
            for(int i = 0;i < 10; i++){
                count++;  
                System.out.println(Thread.currentThread().getName()+": m2's printing : count = "+count);  
            }  
        }
    }
}
却发现结果发生了变化。两个线程都只执行了m1,也就是说flag是
线程独立的。
Thread-0: m1's printing : count = 2
Thread-1: m1's printing : count = 2
Thread-0: m1's printing : count = 3
Thread-1: m1's printing : count = 4
Thread-0: m1's printing : count = 5
Thread-1: m1's printing : count = 6
Thread-0: m1's printing : count = 7
Thread-1: m1's printing : count = 8
Thread-0: m1's printing : count = 9
Thread-1: m1's printing : count = 10
Thread-0: m1's printing : count = 11
Thread-1: m1's printing : count = 12
Thread-0: m1's printing : count = 13
Thread-1: m1's printing : count = 14
Thread-0: m1's printing : count = 15
Thread-1: m1's printing : count = 16
Thread-0: m1's printing : count = 17
Thread-1: m1's printing : count = 18
Thread-0: m1's printing : count = 19
Thread-1: m1's printing : count = 20

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/220851
推荐阅读
相关标签
  

闽ICP备14008679号