zoukankan      html  css  js  c++  java
  • ThreadLocal 实现线程内共享变量

    package com.cn.gbx;
    
    import java.util.Date;
    import java.util.Random;
    import java.util.Timer;
    import java.util.TimerTask;
    
    public class TestThread {
    	static class A{
    		public void get() {
    			User user = User.getInstance();
    			System.out.println("A from " + Thread.currentThread().getName() + " get data:" + user.getName() + " : " + user.getPassword());
    		}
    	}
    	static class B{
    		public void get(){
    			User user = User.getInstance();
    			System.out.println("B from " + Thread.currentThread().getName() + " get data:" + user.getName() + " : " + user.getPassword());
    		}
    	}
    	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() + " : data = " + data);
    						User.getInstance().setName("name:" + data);
    						User.getInstance().setPassword("p:" + data);
    						new A().get();
    						new B().get();   
    						//A,B 模块得到的都是与本线程相关联的数据, 例如数据库connection等等
    					}
    				}
    			).start();
    		}
    	}
    }
    
    class User{
    
    	//类似单例的懒汉模式  其实ThreadLocal 就是一个Map只不过是自动将key设为本地线程
    	private static ThreadLocal<User> threadLocal = new ThreadLocal<User>();
    	private User() {}
    	public static User getInstance() {
    		User user = threadLocal.get();
    		if (user == null) {
    			user = new User();
    			threadLocal.set(user);
    		}
    		return user;
    	}
    	
    	private String name;
    	private String password;
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public String getPassword() {
    		return password;
    	}
    	public void setPassword(String password) {
    		this.password = password;
    	}
    }
    输出:
    
    Thread-1 : data = 1362065454
    Thread-0 : data = 1208952694
    A from Thread-0 get data:name:1208952694 : p:1208952694
    A from Thread-1 get data:name:1362065454 : p:1362065454
    B from Thread-1 get data:name:1362065454 : p:1362065454
    B from Thread-0 get data:name:1208952694 : p:1208952694
    

      

  • 相关阅读:
    【JAVA编码专题】JAVA字符编码系列一:Unicode,GBK,GB2312,UTF-8概念基础
    读取Webpage表中的内容
    各种排序算法的分析及java实现
    运行一个Hadoop Job所需要指定的属性
    Hbase常见异常
    Gora官方文档之二:Gora对Map-Reduce的支持
    Linux 系统挂载数据盘
    Gora快速入门
    Gora官方范例
    在Eclipse中运行Nutch2.3
  • 原文地址:https://www.cnblogs.com/E-star/p/3482032.html
Copyright © 2011-2022 走看看