/**
* 1、就是为每一个使用该变量的线程都提供一个变量值的副本,使每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突
* 2、LocalThread跟线程安全好像没有多大关系,他的作用更多的是起到Session,Request的作用,可以实现大范围内的对象共享(本线程中)
* @author liuze
*/
public class ThreadLocalSample implements Runnable {
private String param;
public ThreadLocalSample(String param) {
this.param = param;
}
public static ThreadLocal<String> offset = new ThreadLocal<String>();
public String getOffset() {
if (offset != null) {
return offset.get();
} else {
return null;
}
}
public void setOffset(String v) {
offset.set(v);
}
public static void main(String[] args) {
ThreadLocalSample a = new ThreadLocalSample("1");
Thread thread1 = new Thread(a);
thread1.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("==========================");
ThreadLocalSample b = new ThreadLocalSample("2");
Thread thread2 = new Thread(b);
thread2.start();
}
@Override
public void run() {
setOffset(param);
System.out.println("the param of current offset is " + getOffset());
}
}
* 1、就是为每一个使用该变量的线程都提供一个变量值的副本,使每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突
* 2、LocalThread跟线程安全好像没有多大关系,他的作用更多的是起到Session,Request的作用,可以实现大范围内的对象共享(本线程中)
* @author liuze
*/
public class ThreadLocalSample implements Runnable {
private String param;
public ThreadLocalSample(String param) {
this.param = param;
}
public static ThreadLocal<String> offset = new ThreadLocal<String>();
public String getOffset() {
if (offset != null) {
return offset.get();
} else {
return null;
}
}
public void setOffset(String v) {
offset.set(v);
}
public static void main(String[] args) {
ThreadLocalSample a = new ThreadLocalSample("1");
Thread thread1 = new Thread(a);
thread1.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("==========================");
ThreadLocalSample b = new ThreadLocalSample("2");
Thread thread2 = new Thread(b);
thread2.start();
}
@Override
public void run() {
setOffset(param);
System.out.println("the param of current offset is " + getOffset());
}
}