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线程隔离
posted @ 2019-08-09 10:46  想念泡凤爪的味道  阅读(273)  评论(0编辑  收藏  举报