package com.huayu.demo; public class Student { private String name; public Student() { } public Student(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + '}'; } }
package com.huayu.demo; public class MyThreadLocal extends ThreadLocal{ @Override protected Object initialValue() { return new Student(); } }
package com.huayu.demo; public class demo0816d { public static void main(String[] args) { ThreadLocal<Student> myThreadLocal = new MyThreadLocal(); Runnable myRun=new Runnable() { @Override public void run() { Student student= myThreadLocal.get(); student.setName(Thread.currentThread().getName()); System.out.println(student.getName()); } }; new Thread(myRun,"线程A").start(); new Thread(myRun,"线程B").start(); new Thread(myRun,"线程C").start(); } }