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
    
  • 相关阅读:
    AtCoder Grand Contest 005F
    AtCoder Regular Contest 095E
    插头DP--URAL1519Formula 1
    「CodePlus 2018 3 月赛」白金元首与莫斯科
    hdu 5795
    hdu 5800
    HDU5802
    hdu 5787 数位dp,记忆化搜索
    poj 1015
    hdu 3092 (简化的素数打表+dp+log的用法) ps(开数组和预处理时数组要大点处理多一点。。。)
  • 原文地址:https://www.cnblogs.com/ssslinppp/p/8036903.html
Copyright © 2011-2022 走看看