七、ThreadLocal

例一:

 1 public class ThreadLocalTest03 {    
 2     private static ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(()-> 1);
 3     public static void main(String[] args) {
 4         new Thread(new MyRun(),"a").start();
 5         new Thread(new MyRun(),"b").start();
 6     }    
 7     public static  class MyRun implements Runnable{
 8         public MyRun() {       //main
 9             threadLocal.set(-100);
10             System.out.println(Thread.currentThread().getName()+"-->"+threadLocal.get());    
11         }
12         public void run() {
13             System.out.println(Thread.currentThread().getName()+"-->"+threadLocal.get());    
14             //new Thread(new MyRunxxx()).start();
15         }
16     }
17     
18 }

例二:操作数据库

 1 import java.sql.Connection;
 2 import java.sql.DriverManager;
 3 import java.sql.SQLException;
 4 
 5 public class DBUtil3 {
 6     private static final String DRIVER="com.mysql.jdbc.Driver";
 7     private static final String    USER="root";
 8     private static final String PWD="root";
 9     private static final String URL="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
10     
11     //定义一个数据库连接
12     private static Connection conn=null;
13     private static ThreadLocal<Connection> connContainer=new ThreadLocal<Connection>(){
14         protected Connection initialValue() {
15             try {
16                 Class.forName(DRIVER);
17                 
18                 if(conn==null){
19                     
20                     conn=DriverManager.getConnection(URL, USER, PWD);
21                 }
22                 
23             } catch (ClassNotFoundException e) {
24                 // TODO Auto-generated catch block
25                 e.printStackTrace();
26             } catch (SQLException e) {
27                 // TODO Auto-generated catch block
28                 e.printStackTrace();
29             } 
30             return conn;
31         };
32     };
33     //获取连接
34     public   static Connection getConnection(){
35         return connContainer.get(); //获取连接
36         
37     }
38     //关闭连接的方法
39     public   static void colseConnection(){
40         if (conn!=null) {
41             try {
42                 conn.close();
43             
44             } catch (SQLException e) {
45                 // TODO Auto-generated catch block
46                 e.printStackTrace();
47             }
48             
49         }
50     }
51     public static void main(String[] args) {
52         System.out.println(getConnection());
53     }
54 }

例二:

原文地址:https://www.cnblogs.com/qiaoxin11/p/12721689.html