public class use {
public static void main(String[] args) {
book b1 = new book();
myThread1 t1 = new myThread1(b1);
myThread2 t2 = new myThread2(b1, t1);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
// 线程类1
class myThread1 extends Thread {
book b;
public myThread1(book b) {
super();
this.b = b;
}
@Override
public void run() {
int i = 0;
try {
while(true){
System.out.println(Thread.currentThread().getName()+"="+book.t.get());
book.t.set(i++);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// 线程类2
class myThread2 extends Thread {
book b;
myThread1 t1;
public myThread2(book b, myThread1 t1) {
this.b = b;
this.t1 = t1;
}
@Override
public void run() {
int i = 20;
while (true) {
System.out.println(Thread.currentThread().getName()+"="+book.t.get());
book.t.set(i++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
// 资源类
class book {
public static ThreadLocal t = new ThreadLocal();
}
很明显每一个线程自己的ThreadLocal里面存的值不同,所以不是用来做线程共享的。
他有三个方法:
set、get、remove
线程调用,就会创建、获取值、删除自己对应的值。
主要用于servlet之中的请求request域之类的地方。