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线程隔离
  • 相关阅读:
    SQL2005四个排名函数(row_number、rank、dense_rank和ntile)的比较
    LINQ to List泛型的几种简单查询
    sql语句精选
    C#利用QrCode.Net生成二维码(Qr码)
    LINQ to XML CRUD,并且封装为DAL方法
    vim编辑器
    去年的烟花特别多……
    年初七
    活死人黎明 Dawn of the Dead
    在碟片里奔驰我的看碟人生
  • 原文地址:https://www.cnblogs.com/pretttyboy/p/11325748.html
Copyright © 2011-2022 走看看