java--本地线程

同一个线程(用户)拿到同一个对象

package cn.hncu.threadLocalUtil;

import java.util.Random;

public class ThreadLocalUtil {

    private static ThreadLocal t=new ThreadLocal();
    //下面这一句是演示使用我们自己的MyThreadlocal
    //线程管理池  Map
//  private static MyThreadLocal t=new MyThreadLocal();
    public static Object getObj(){
        Object obj=t.get();
        if(obj==null){
            Random r=new Random();
            obj=r.nextInt(200);
            t.set(obj);
        }
        return obj;
    }
}
 
  
package cn.hncu.threadLocalUtil;

public class Hello {

    public static void print(){
        Object obj3=ThreadLocalUtil.getObj();
        Object obj4=ThreadLocalUtil.getObj();
        System.out.println("obj3:"+obj3);
        System.out.println("obj4:"+obj4);
        System.out.println(obj3==obj4);

    }

}
package cn.hncu.threadLocalUtil;

import org.junit.Test;

public class Client {

    @Test
    public void ma() {
        Object obj1=ThreadLocalUtil.getObj();
        Object obj2=ThreadLocalUtil.getObj();
        System.out.println("obj1:"+obj1);
        System.out.println("obj2:"+obj2);
        System.out.println(obj1==obj2);

    }
    //测试结果: obj1,obj2,obj3和obj4都是同一个对象 ----因为它们是同一个线程
    //       obj5和obj6是同一个对象,但 这两个对象和上面的obj1~obj4是不同的。因为这两个是另一个线程中获取出来的
    @Test
    public void threadDemo(){
        Object obj1=ThreadLocalUtil.getObj();
        Object obj2=ThreadLocalUtil.getObj();
        System.out.println("obj1:"+obj1);
        System.out.println("obj2:"+obj2);
        System.out.println(obj1==obj2);

        Hello.print();
        System.out.println("======");

        new Thread(){
            public void run(){
                Object obj5=ThreadLocalUtil.getObj();
                Object obj6=ThreadLocalUtil.getObj();
                System.out.println("obj5:"+obj5);
                System.out.println("obj6:"+obj6);
                System.out.println(obj5==obj6);
            }
        }.start();

    }

}

理解ThreadLocal原理,写一个MyThreadLocal模拟ThreadLocal类的原理功能

package cn.hncu.threadLocalUtil;

import java.util.HashMap;
import java.util.Map;

//自己模拟ThreadLocal的功能,便于大家理解该类。
//承认:虽然我们把表面功能模拟出来,但ThreadLocal真正的功能远远比这强,比如内存管理
public class MyThreadLocal<Object> {

    Map< Thread, Object> map=new HashMap<Thread, Object>();
    public Object get(){
        Thread t=Thread.currentThread();
        return map.get(t);
    }
    public void set(Object obj){
        Thread t=Thread.currentThread();
        map.put(t, obj);
    }
}

你可能感兴趣的:(mysql,java--后台)