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
    
  • 相关阅读:
    图论一角
    入门-k8s部署应用 (三)
    入门-k8s集群环境搭建(二)
    入门-Kubernetes概述 (一)
    shell中获取时间
    Linux shell脚本之 if条件判断 (转)
    linux中shell变量$#等的释义
    shell 的here document 用法 (cat << EOF) (转)
    Homebrew的安装与使用
    docker容器编排 (4)
  • 原文地址:https://www.cnblogs.com/ssslinppp/p/8036903.html
Copyright © 2011-2022 走看看