zoukankan      html  css  js  c++  java
  • ThreadLocal线程隔离

     1 package com.cookie.test;
     2 import java.util.concurrent.atomic.AtomicInteger;
     3 /**
     4  * author : cxq
     5  * Date : 2019/6/20
     6  * 测试ThreadLocal线程隔离
     7  */
     8 public class ThreadLocalTest {
     9     private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
    10     private static AtomicInteger a = new AtomicInteger(100);
    11     private static int b = 100 ;
    12     public static void main(String[] args) {
    13         new Thread(() -> {
    14             try {
    15                 for (int i = 0; i < 100; i++) {
    16                     threadLocal.set(i);
    17 // a.decrementAndGet();
    18                     b -- ;
    19                     System.out.println(Thread.currentThread().getName() + "====" + threadLocal.get());
    20 // System.out.println(Thread.currentThread().getName() + "====" + a.get());
    21 // System.out.println(Thread.currentThread().getName() + "====" + b);
    22                     try {
    23                         Thread.sleep(100);
    24                     } catch (InterruptedException e) {
    25                         e.printStackTrace();
    26                     }
    27                 }
    28             } finally {
    29                 threadLocal.remove();
    30             }
    31         }, "threadLocal1").start();
    32         new Thread(() -> {
    33             try {
    34                 for (int i = 0; i < 100; i++) {
    35                     System.out.println(Thread.currentThread().getName() + "====" + threadLocal.get());
    36 // System.out.println(Thread.currentThread().getName() + "====" + a.get());
    37                     System.out.println(Thread.currentThread().getName() + "====" + b);
    38                     try {
    39                         Thread.sleep(100);
    40                     } catch (InterruptedException e) {
    41                         e.printStackTrace();
    42                     }
    43                 }
    44             } finally {
    45                 threadLocal.remove();
    46             }
    47         }, "threadLocal2").start();
    48     }
    49 }

    输出结果展示:

    ThreadLocal线程隔离

     

    如果采用AtomicInteger a 或者常量 int b :

    ThreadLocal线程隔离
  • 相关阅读:
    Nginx源码编译安装
    nginx版本对比
    k8s中subpath挂载单个文件报错处理
    C++ array 数组函数
    洛谷 P2141
    c++ set容器
    字符串中输出每一个元素的方法
    string中的pop_back()函数
    如何去掉前导0 在字符串中 算法
    pat 乙级1074
  • 原文地址:https://www.cnblogs.com/pretttyboy/p/11325748.html
Copyright © 2011-2022 走看看