zoukankan      html  css  js  c++  java
  • 【ThreadLocal】使用ThreadLocal实现线程安全

    非线程安全

    public class UnSafeThreadLocalDemo {
        private int count = 0;
    
        public static void main(String[] args) {
            UnSafeThreadLocalDemo unSafeThreadLocalDemo = new UnSafeThreadLocalDemo();
            for (int i = 0; i < 5; i++) {
                int finalI = i;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        unSafeThreadLocalDemo.process();
                        unSafeThreadLocalDemo.print(finalI);
                    }
                }).start();
            }
    
        }
    
        public void process() {
            for (int i = 0; i < 10; i++) {
                count += 1;
                try {
                    TimeUnit.MILLISECONDS.sleep(new Random().nextInt(10) + 10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    
        }
    
        public void print(int i) {
            System.out.println("count(" + i + ") = " + count);
        }
    }
    

    输出:

    count(1) = 44
    count(0) = 46
    count(3) = 47
    count(2) = 49
    count(4) = 49
    

    线程安全

    public class SafeThreadLocalDemo {
        //    private int count = 0;
        private ThreadLocal<Integer> count = new ThreadLocal<Integer>() {
            protected Integer initialValue() {
                return 0;
            }
        };
    
        public void process() {
            for (int i = 0; i < 10; i++) {
                count.set(count.get() + 1);
                try {
                    TimeUnit.MILLISECONDS.sleep(new Random().nextInt(10) + 10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    
        }
    
        public void print(int i) {
            System.out.println("count(" + i + ") = " + count.get());
        }
    
        public static void main(String[] args) {
            SafeThreadLocalDemo safeThreadLocalDemo = new SafeThreadLocalDemo();
            for (int i = 0; i < 5; i++) {
                int finalI = i;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        safeThreadLocalDemo.process();
                        safeThreadLocalDemo.print(finalI);
                    }
                }).start();
            }
    
        }
    }
    

    输出:

    count(1) = 10
    count(0) = 10
    count(2) = 10
    count(4) = 10
    count(3) = 10
    
  • 相关阅读:
    Building fresh packages卡很久
    后端阿里代码扫描
    npm 使用淘宝镜像
    git镜像
    mysql安装8.0.18
    idea2019.2.2版本破解
    JDK下载很慢
    解决GitHub下载速度慢下载失败的问题
    Hashtable多线程遍历问题
    2-18 求组合数 注:代码有问题找不出哪儿错了
  • 原文地址:https://www.cnblogs.com/ssslinppp/p/8036903.html
Copyright © 2011-2022 走看看