• Java ThreadLocal 使用场景一


     1 /**
     2      * @param args
     3      * @throws InterruptedException 
     4      */
     5     public static void main(String[] args) throws InterruptedException {
     6         
     7         
     8         //ThreadLocal使用背景之一
     9         /***
    10          比如想在一个线程执行当中的任何地方都可以找到某一个变量的值,而且别的线程不能有任何的干预,
    11          如果不使用ThreadLocal类似方法的话
    12         那么这个变量必须在之间互相传递.
    13          */
    14         final ThreadLocal sample1 = new ThreadLocal();
    15         
    16         for(int i = 0; i < 5;i++){
    17             new Thread(){
    18                 
    19                 public void run(){
    20                     business1();
    21                     System.out.println(sample1.get());
    22                     business2();
    23                     
    24                     try {
    25                         Thread.currentThread().sleep(1000);
    26                         //为了说明每个线程对sample1内的值互补干涉,如果干涉,一定是最后一个线程id睡觉
    27                     } catch (InterruptedException e) {
    28                         e.printStackTrace();
    29                     }
    30                     System.out.println(sample1.get());
    31                 }
    32                 
    33                 //这个线程内,可能是别的类要执行的业务方法
    34                 public void business1(){
    35                     sample1.set(Thread.currentThread().getId() +"吃饭");
    36                 }
    37                 //这个线程内,可能是更远的类要执行的业务方法
    38                 public void business2(){
    39                     sample1.set(Thread.currentThread().getId() + "睡觉");
    40                 }
    41                 
    42             }.start();
    43             
    44         }

    8吃饭
    9吃饭
    10吃饭
    11吃饭
    12吃饭
    8睡觉
    9睡觉
    11睡觉
    10睡觉
    12睡觉

  • 相关阅读:
    Yarn的运行原理(执行流程)
    Hive 表类型简述
    hive 表类型
    Hadoop小知识点总结1
    电商交易项目案例
    乘用车辆和商用车辆销售数据分析
    搜狗搜索日志分析系统
    mysql group by 对多个字段进行分组
    group by
    输出GPLT
  • 原文地址:https://www.cnblogs.com/harrison2010/p/2976273.html
Copyright © 2020-2023  润新知