多线程ThreadLocal

线程隔离
在多线程并发的环境下,每个线程中的变量都是相互独立的
线程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让变量每次在使用的时候,都从主存中取。而不是从各个线程的“工作内存”。保证了可见性,一个线程修改了线程共享变量的值,其它线程能够立即得知这个修改。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值