栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

多线程ThreadLocal

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

多线程ThreadLocal

线程隔离:
在多线程并发的环境下,每个线程中的变量都是相互独立的
线程A:设置(变量1) 获取(变量1)
线程B:设置(变量2) 获取(变量2)

ThreadLocal: 若不用这种方式设置变量,当AB线程共享同一个变量的时候,会产生A线程拿到本在B线程中变量的值,造成变量值的混乱
1.set(xxx):将变量绑定到当前线程中
2.get():获取当前线程绑定的变量

1、继承Thread类

public class MyThread extends Thread{  

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/351665.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号