线程隔离:
在多线程并发的环境下,每个线程中的变量都是相互独立的
线程A:设置(变量1) 获取(变量1)
线程B:设置(变量2) 获取(变量2)
ThreadLocal: 若不用这种方式设置变量,当AB线程共享同一个变量的时候,会产生A线程拿到本在B线程中变量的值,造成变量值的混乱
1.set(xxx):将变量绑定到当前线程中
2.get():获取当前线程绑定的变量
1、继承Thread类
public class MyThread extends Thread{
ThreadLocal<String> t1 = new ThreadLocal<>();
private String status;
public String getStatus() {
//return status;
return t1.get();
}
public void setStatus(String status) {
//this.status = status;
//变量status绑定到当前线程中
t1.set(status)
}
@Override
public void run() {
System.out.println("Mythread执行");
}
}
public class TestMain {
public static void main(String[] args) {
MyThread mythread = new MyThread();
mythread.start();
MyThread mythread2 = new MyThread();
mythread2.start();
}
}
2、实现Runnable接口
public class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("MyRunnable执行");
}
}
public class TestMain {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
Thread thread2 = new Thread(new MyRunnable());
thread2.start();
}
}
volatile关键字的作用:
private volatile String name;
volatile让变量每次在使用的时候,都从主存中取。而不是从各个线程的“工作内存”。保证了可见性,一个线程修改了线程共享变量的值,其它线程能够立即得知这个修改。