- package cn.javastudy.p19.threadlocal.demo;
- import java.util.Timer;
- import java.util.TimerTask;
- public class ThreadDemo {
- /**
- * @param args
- */
- public static void main(String[] args) {
- //线程一:
- Thread t1=new Thread(new Runnable(){
- @Override
- public void run() {
- // TODO Auto-generated method stub
- Model1.set("张三", 25);
- Model1.get();
- }});
- t1.start();
- //线程二:
- Thread t2=new Thread(new Runnable(){
- @Override
- public void run() {
- // TODO Auto-generated method stub
- Model2.set("李四", 30);
- Model2.get();
- }});
- t2.start();
- }
- //根据线程获取对应的对象,然后操作对象
- static class Model1{
- public static void set(String name,int age)
- {
- ThreadLocalDemo.getThreadInstance().setName(name);
- ThreadLocalDemo.getThreadInstance().setAge(age);
- }
- public static void get()
- {
- System.err.println(Thread.currentThread().getName()+": name:"+ThreadLocalDemo.getThreadInstance().getName()+"age:"+ThreadLocalDemo.getThreadInstance().getAge());
- }
- }
- //根据线程获取对应的对象,然后操作对象
- static class Model2{
- public static void set(String name,int age)
- {
- ThreadLocalDemo.getThreadInstance().setName(name);
- ThreadLocalDemo.getThreadInstance().setAge(age);
- }
- public static void get()
- {
- System.err.println(Thread.currentThread().getName()+": name:"+ThreadLocalDemo.getThreadInstance().getName()+"age:"+ThreadLocalDemo.getThreadInstance().getAge());
- }
- }
- //线程的共享数据类
- static class ThreadLocalDemo{
- private static ThreadLocal<ThreadLocalDemo> threadLocal =new ThreadLocal<ThreadLocalDemo>();
- private ThreadLocalDemo(){}
- private static ThreadLocalDemo tld=null;
- private String name;
- private int age;
- public static ThreadLocalDemo getThreadInstance()
- {
- tld=threadLocal.get();
- if(tld==null)
- {
- tld=new ThreadLocalDemo();
- threadLocal.set(tld);
- }
- return tld;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
- }
复制代码 ThreadLocal实现了线程的多个模块的数据的共享。使每个线程的各个数据独立存在,减少了线程的安全隐患。三根据线程的不同而自由切换。 |