【多线程】-线程范围内共享数据的两种方式
来源:互联网 发布:三星5830root软件 编辑:程序博客网 时间:2024/05/15 06:02
第一种,声明一个全局的map变量,用来存当前线程范围内的变量,用于线程范围内使用
//线程范围内共享变量public class ThreadScopeShareData {//声明一个存放全局变量的容器,来保存该变量在该线程范围内的状态private static Map<Thread, Integer> threadData = new HashMap<Thread, Integer>();public static void main( String[] args){for (int i = 0; i < 2; i++) {new Thread(new Runnable() {@Overridepublic void run() {int data = new Random().nextInt();System.out.println(Thread.currentThread().getName() + "has put data:" + data);threadData.put(Thread.currentThread(), data);new A().get();new B().get();}}).start();}}static class A{public void get(){int data = threadData.get(Thread.currentThread());System.out.println("A from" + Thread.currentThread().getName() + "get data:" + data);}}static class B{public void get(){int data = threadData.get(Thread.currentThread());System.out.println("A from" + Thread.currentThread().getName() + "get data:" + data);}}}
第二种,采用threadlocal方式(threadlocal这种变量,一个变量只能对应一个threadlocal,threadlocal原理其实就是一个map同上)
//线程范围内共享数据public class ThreadLocalTest { //定义一个threadlocal变量,该threadlocal变量其实就相当于一个map private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>(); public static void main( String[] args){ for (int i = 0; i < 2; i++) { new Thread(new Runnable() { @Override public void run() { int data = new Random().nextInt(); System.out.println(Thread.currentThread().getName() + "has put data:" + data); //将数据存到当前线程里面 threadLocal.set(data); new A().get(); new B().get(); } }).start(); } } static class A{ public void get(){ int data = threadLocal.get(); System.out.println("A from" + Thread.currentThread().getName() + "get data:" + data); } } static class B{ public void get(){ int data = threadLocal.get(); System.out.println("A from" + Thread.currentThread().getName() + "get data:" + data); } }}
阅读全文
0 0
- 【多线程】-线程范围内共享数据的两种方式
- 多线程之线程范围内的数据共享ThreadLocal
- Java基础:多线程之线程范围内的数据共享ThreadLocal
- java多线程:5、线程范围内的数据共享_ThreadLocal
- 线程范围内的数据共享
- 多线程_线程范围内数据共享
- 线程范围内共享数据
- 线程范围内数据共享
- 线程范围内共享数据
- 线程范围内共享数据
- ThreadLocal实现线程范围内的数据共享
- 线程范围内的共享数据 ThreadLocal
- 《黑马程序员》线程范围内的数据共享
- java线程范围内的数据共享
- ThreadLocal-------线程范围内的数据共享
- 多线程并发库高级应用 之 线程范围内共享数据
- 多线程并发库高级应用 之 线程范围内共享数据
- 多线程学习(四)-线程范围内共享数据
- 封装OkHttpUtil
- kuangbin专题五 并查集 POJ3038 How Many Answers Are Wrong
- Long Dominoes (状态dp)
- 12月1号
- 爬糗事百科的段子(爬多页)
- 【多线程】-线程范围内共享数据的两种方式
- c#多线程_1
- 用树莓派搭建svn服务器
- 基于单片机的LED流水灯(着力解决加速减速bug问题)
- 添加表单姓名邮箱
- [INS-06006] Passwordless SSH connectivity not set up between the following node(s):
- 京东商城的分类
- 快速排序 C语言描述
- angular4系列之国际化