ThreadLocal的一个简单实例

数据源
package threadApi.bean;

public class NumberBean {
	private  int id = 0 ;

	public   int getId() {
		return id;
	}

	public  void  setId(int id) {
		this.id = id;
	} 
}

ThreadLocal类
package threadLocalBean;

import threadApi.bean.NumberBean;

public class ThreadLocalTest{
	// 定义匿名子类创建ThreadLocal的变量为什么是静态的,不管你new多少个这个类,ThreadLocal只有一个
	private static ThreadLocal<NumberBean> seqNum = new ThreadLocal<NumberBean>() {
		// 覆盖初始化方法,泛型指定什么类型就返回什么类型,方法名不变自动调用。
		public NumberBean initialValue() {
			System.out.println("初始化了");
			return new NumberBean();
		}
	};

	// 或者这线程的数据
	public NumberBean  getNextNum() {    
	    return seqNum.get();  
	}
	
}

线程类
package threadLocalBean;

public class ThreadBean01 extends Thread {
	private ThreadLocalTest te;
	public ThreadBean01(String name, ThreadLocalTest te) {
		super(name);
		this.te = te;
	}
	@Override
	public void run() {
		while (te.getNextNum().getId() < 100) {
			te.getNextNum().setId(te.getNextNum().getId() + 1);
			System.out.println(this.getName() + "数字: " + te.getNextNum().getId());
		}
	}
	public ThreadLocalTest getTe() {
		return te;
	}
	public void setTe(ThreadLocalTest te) {
		this.te = te;
	}
}

测试类
package threadApi;
import threadLocalBean.ThreadBean01;
import threadLocalBean.ThreadLocalTest;
public class Test11 {
	public static void main(String[] args) {	
		ThreadLocalTest local = new ThreadLocalTest();
		ThreadBean01 thread01 = new ThreadBean01("线程一",local);
		ThreadBean01 thread02 = new ThreadBean01("线程二",local);
		thread01.start();
		thread02.start();	
	}

}
运行效果
初始化了
初始化了
线程一数字: 1
线程一数字: 2
线程一数字: 3
线程一数字: 4
线程二数字: 1
线程二数字: 2
线程二数字: 3
线程二数字: 4
线程二数字: 5
线程二数字: 6


  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值