【多线程】-线程范围内共享数据的两种方式

第一种,声明一个全局的map变量,用来存当前线程范围内的变量,用于线程范围内使用

 

//线程范围内共享变量
public class ThreadScopeShareData {
	
	//声明一个存放全局变量的容器,来保存该变量在该线程范围内的状态
	private static Map threadData = new HashMap();
	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);
					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 threadLocal = new ThreadLocal();
	        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);
	                        
	                }
	        }
	}

 

 

 

 

 

 

你可能感兴趣的:(❀❀❀❀❀❀-并发)