ThreadLocal

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>(){
		@Override
		protected Integer initialValue() {
			return num;
		};
	};
	//读取该变量时,则是从ThreadLocal实例中去读(每个线程读到的是自己操作的变量副本)
	public static int getNum(){
		return threadLocal.get();
	}
	//定义读取变量值的线程
	public static class TestThread extends Thread{
		public TestThread(){
			this.setName("TestThread");
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
			for (int i = 0; i < 5; i++) {
				System.out.println(this.getName()+"---->"+getNum());
				try {
					//线程调度均匀些
					sleep(3);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	//定义改变变量值的线程(增加)
	public static class TestThreadAdd extends Thread{
		public TestThreadAdd(){
			this.setName("TestThreadAdd");
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
			for (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 block
					e.printStackTrace();
				}
			}
		}
	}
	//定义改变变量值的线程(减少)
	public static class TestThreadSub extends Thread{
		public TestThreadSub(){
			this.setName("TestThreadSub");
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
			for (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 block
					e.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
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zz_cl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值