packagecom.threadlocal;publicclassT1{// 创建ThreadLocal对象,publicstaticThreadLocal<Object> threadLocal =newThreadLocal<>();// Task是线程类, 内部类publicstaticclassTaskimplementsRunnable{@Overridepublicvoidrun(){Dog dog =newDog();//给threadloca对象中放入dog对象
threadLocal.set(dog);Object o = threadLocal.get();System.out.print("在Task中,run方法内的线程为"+Thread.currentThread().getName());System.out.println(" dog="+ o);newT1Service().update();}}publicstaticvoidmain(String[] args){newThread(newTask()).start();}}
packagecom.threadlocal;publicclassT1Service{publicvoidupdate(){Object o =T1.threadLocal.get();System.out.print("在T1Service的update()中的线程为"+Thread.currentThread().getName());System.out.println(" dog= "+ o);// 再在T1Service中调用T1DAOnewT1DAO().update();}}
packagecom.threadlocal;publicclassT1DAO{publicvoidupdate(){Object o =T1.threadLocal.get();System.out.print("在T1DAO的update中线程名称为"+Thread.currentThread().getName());System.out.println("在T1DAO中的dog="+ o);}}