• JDBC: ThreadLocal 类


    1、ThreadLocal

    ThreadLocal用于保存某个线程共享变量。在Java中,每个线程对象都有一个ThreadLocal<ThreadLocal,Object>,其中key就是一个ThreadLocal,而Object就是线程的共享变量。对于同一个static ThreadLocal,不同的线程只能从中get,set,remove自己的变量,而不会影响其他线程的变量。

    在Java的多线程编程中,为保证多个线程对共享变量的安全访问,通常会使用synchronized来保证同一时刻只有一个线程对共享变量进行操作。这种情况下可以将类变量放到ThreadLocal类型的对象中,使变量在每个线程中都有独立拷贝,不会出现一个线程读取变量时而被另一个线程修改的现象。最常见的ThreadLocal使用场景为用来解决数据库连接、Session管理等。
    package com.dgd.test;
    
    import java.util.Random;
    
    public class TestTools {
        public static void main(String[] args) {
            MyThread th1=new MyThread();
            th1.start();
    
            MyThread th2=new MyThread();
            th2.start();
        }
    }
    
    class  Tools{
        private  static Random rand=new Random();
        private  static ThreadLocal<Integer> th=new ThreadLocal<>();
    
        public  static  void setNumber()
        {
            th.set(rand.nextInt(100));
            //这里设置的就是当前线程保存的共享变量,这个共享变量不是之前的多线程之间的共享变量,而是同一个线程在整个生命周期中,使用的共享变量。
        }
        public  static int getNumber(){
            return th.get();
        }
    }
    class MyThread extends Thread{
        public  void  run(){
            Tools.setNumber();
            for (int i = 0; i <5 ; i++) {
                int number=Tools.getNumber();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread()+":"+number);
            }
        }
    }
     
  • 相关阅读:
    测试
    Python 学习笔记【15】文件操作
    Python 学习笔记【14】集合
    Python 学习笔记【13】练习:三级菜单
    Python 学习笔记【12】字典
    Python 学习笔记【11】字符串操作
    Python 学习笔记【10】练习:购物车程序
    Python 学习笔记【09】列表、元组
    Python 学习笔记【08】数据类型、数据运算、进制转换
    Python 学习笔记【07】PEP 8 中英对照
  • 原文地址:https://www.cnblogs.com/lemonzhang/p/12812861.html
Copyright © 2020-2023  润新知