ThreadLocal
,它可以在一个线程中传递同一个对象
学习链接:使用ThreadLocal - 廖雪峰的官方网站
eg:
public class ThreadLocalDemo {public static void main(String[] args) throws InterruptedException {Thread t1 = new Thread(new StudentThread("甄嬛",17, 98));Thread t2 = new Thread(new StudentThread("夏冬春", 17, 58));t1.setName("T0");t2.setName("T1");t1.start();t2.start();Thread.sleep(1000);System.out.println("测试完成");}
}class Student {private String name;private int age;private int score;public Student(String name, int age, int score) {this.name = name;this.age = age;this.score = score;}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;}public int getScore() {return score;}public void setScore(int score) {this.score = score;}
}//把ThreadLocal封装在StudentTaske中,实现AutoCloseable接口,可以使用try(source){...}结构
/*因为当前线程执行完相关代码后,很可能会被重新放入线程池中,
如果ThreadLocal没有被清除,该线程执行其他代码时,会把上一次的状态带进去。*/
class StudentTask implements AutoCloseable {static final ThreadLocal<Student> stu = new ThreadLocal<>();//设置一个Student实例关联到ThreadLocal中public StudentTask(String name, int age, int score) {stu.set(new Student(name, age, score));}//静态方法包装get()public static Student currentStudent() {return stu.get();}//让编译器自动移除与ThreadLocal关联的实例@Overridepublic void close() {stu.remove();}
}class StudentThread implements Runnable {private String name;private int age;private int score;public StudentThread(String name, int age, int score) {this.name = name;this.age = age;this.score = score;}@Overridepublic void run() {//try(source){...}结构,结束后自动释放与ThreadLocal关联的实例//在移除之前,所有方法都可以随时获取到该Student实例try (StudentTask task = new StudentTask(this.name, this.age, this.score)) {step1();step2();log();}}void step1() {//获取到当前线程局部变量的Student实例Student stu = StudentTask.currentStudent();System.out.println(Thread.currentThread()+" 步骤一,学生姓名:" + stu.getName());System.out.println(Thread.currentThread()+" 步骤1完成");}void step2() {Student stu = StudentTask.currentStudent();System.out.println(Thread.currentThread()+" 步骤二," + stu.getName() + "年龄" + stu.getAge());System.out.println(Thread.currentThread()+" 步骤2完成");}void log() {Student stu = StudentTask.currentStudent();String grade = stu.getScore() > 60 ? " GOOD!" : " OH NO!";System.out.println(Thread.currentThread()+" 步骤三,"+stu.getName() + "的成绩等级为" + grade);System.out.println(Thread.currentThread()+" 步骤3完成");}
}