ThreadLocal

来源:互联网 发布:中国人民大学新闻 知乎 编辑:程序博客网 时间:2024/04/29 18:20

ThreadLocal类提供了线程局部变量。这些变量在每个线程访问它时都有自己的方法,独立地初始化变量的副本。将变量与当前线程绑定。

package com.frame.test;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class ThreadLocalTest {//定义一个将会被多个线程操作到的变量private static int num=0;//初始化一个ThreadLocal实例,去指向并持有该变量static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>(){@Overrideprotected Integer initialValue() {return num;};};//读取该变量时,则是从ThreadLocal实例中去读(每个线程读到的是自己操作的变量副本)public static int getNum(){return threadLocal.get();}//定义读取变量值的线程public static class TestThread extends Thread{public TestThread(){this.setName("TestThread");}@Overridepublic void run() {// TODO Auto-generated method stubfor (int i = 0; i < 5; i++) {System.out.println(this.getName()+"---->"+getNum());try {//线程调度均匀些sleep(3);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}//定义改变变量值的线程(增加)public static class TestThreadAdd extends Thread{public TestThreadAdd(){this.setName("TestThreadAdd");}@Overridepublic void run() {// TODO Auto-generated method stubfor (int i = 0; i < 5; i++) {threadLocal.set(getNum()+1);System.out.println(this.getName()+"---->"+(getNum()));try {sleep(3);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}//定义改变变量值的线程(减少)public static class TestThreadSub extends Thread{public TestThreadSub(){this.setName("TestThreadSub");}@Overridepublic void run() {// TODO Auto-generated method stubfor (int i = 0; i < 5; i++) {threadLocal.set(getNum()-1);System.out.println(this.getName()+"---->"+(getNum()));try {sleep(3);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}} }public static void main(String[] args) {ExecutorService executorService = Executors.newFixedThreadPool(3);executorService.execute(new TestThread());executorService.execute(new TestThreadAdd());executorService.execute(new TestThreadSub());}}
输出


最常见的ThreadLocal使用场景为 用来解决 数据库连接、Session管理等。

private static ThreadLocal<Connection> connectionHolder= new ThreadLocal<Connection>() {public Connection initialValue() {    return DriverManager.getConnection(DB_URL);}}; public static Connection getConnection() {return connectionHolder.get();}


0 0
原创粉丝点击