欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

让人困惑的ThreadLocal 博客分类: j2ee ThreadLocaljava多线程

程序员文章站 2024-02-17 09:57:58
...

目前网上介绍ThreadLocal类用法的博文很多,看过后我们基本可以得出以下结论

ThreadLocal的作用和目的:
用于实现线程内的数据共享,即对于相同的程序代码,多个模块在同一个线程中运行时要共享一份数据,而在另外线程中运行时又共享另外一份数据。

好了,至此ThreadLocal的概念我们弄清了,它是每个线程的菊部变量(该死的输入法)。但是java有了类的局部变量,这个ThreadLocal是否显得多余,我们为什么或者在什么情况下用这个东西?

先看以下两段代码

 

代码1.使用ThreadLocal

 

public class ThreadLocalDemo implements Runnable {

	private final static ThreadLocal<Integer> tLocal = new ThreadLocal<Integer>();

	public static void main(String[] agrs) {
		ThreadLocalDemo td = new ThreadLocalDemo();
		Thread t1 = new Thread(td, "t1");
		Thread t2 = new Thread(td, "t2");
		t1.start();
		t2.start();
	}

	/**
	 * 示例业务方法
	 */
	public void test() {
		while (true) {
			try {
				Integer b = (Integer) tLocal.get();
				if (b == null) {
					b = 0;
					tLocal.set(b);
				}
				String currentThreadName = Thread.currentThread().getName();
				System.out.println("thread " + currentThreadName + " set value to:" + b++);
				tLocal.set(b);
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

	@Override
	public void run() {
		test();
	}

}

运行结果: 

thread t2 set value to:0
thread t1 set value to:0
thread t1 set value to:1
thread t2 set value to:1
thread t1 set value to:2
thread t2 set value to:2
thread t1 set value to:3
thread t2 set value to:3

 

代码2.使用局部变量

 

public class ThreadLocalDemoMutli implements Runnable {

	private int a = 0;

	public static void main(String[] agrs) {
		ThreadLocalDemoMutli td = new ThreadLocalDemoMutli();
		ThreadLocalDemoMutli td2 = new ThreadLocalDemoMutli();
		Thread t1 = new Thread(td, "t1");
		Thread t2 = new Thread(td2, "t2");
		t1.start();
		t2.start();
	}

	/**
	 * 示例业务方法,用来测
	 */
	public void test() {
		while (true) {
			try {
				String currentThreadName = Thread.currentThread().getName();
				System.out.println("thread " + currentThreadName + " set age to:" + a++);
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

	@Override
	public void run() {
		test();
	}
}

 运行结果

 

thread t1 set age to:0
thread t2 set age to:0
thread t1 set age to:1
thread t2 set age to:1
thread t2 set age to:2
thread t1 set age to:2
thread t1 set age to:3
thread t2 set age to:3

 

感觉用不用结果都一样嘛?再看下面代码

代码3

public class ThreadLocalDemoSingle implements Runnable {

	private int a = 0;

	public static void main(String[] agrs) {
		ThreadLocalDemoSingle td = new ThreadLocalDemoSingle();
		Thread t1 = new Thread(td, "t1");
		Thread t2 = new Thread(td, "t2");
		t1.start();
		t2.start();
	}

	/**
	 * 示例业务方法,用来测
	 */
	public void test() {
		while (true) {
			try {
				String currentThreadName = Thread.currentThread().getName();
				System.out.println("thread " + currentThreadName + " set age to:" + a++);
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

	@Override
	public void run() {
		test();
	}
}

 运行结果:

thread t1 set age to:0
thread t2 set age to:1
thread t1 set age to:2
thread t2 set age to:3
thread t1 set age to:4
thread t2 set age to:5
thread t1 set age to:6
thread t2 set age to:7
thread t1 set age to:8
thread t2 set age to:9
thread t2 set age to:10
thread t1 set age to:11

 这回不一样了,对比代码2与代码3的区别就在于创建线程的时候

代码2里

ThreadLocalDemoMutli td = new ThreadLocalDemoMutli();
ThreadLocalDemoMutli td2 = new ThreadLocalDemoMutli();
		Thread t1 = new Thread(td, "t1");
		Thread t2 = new Thread(td2, "t2");

 代码3里

ThreadLocalDemoSingle td = new ThreadLocalDemoSingle();
		Thread t1 = new Thread(td, "t1");
		Thread t2 = new Thread(td, "t2");

 只不过多new了一个对象,原因也一眼看的清楚,但是始终没回答为什么要用ThreadLocal

 

 

 

看来只能从框架里找找原因了,下面搬出hibernate源码(我已经修改了很多)

代码4

public class HibernateUtil {

    //创建线程局部变量session,用来保存Hibernate的Session
    public static final ThreadLocal<Integer> session = new ThreadLocal<Integer>();
    
    public static Integer s2=0;
 
    /**
     * 获取当前线程中的Session
     * @return Session
     * @throws HibernateException
     */
    public static Integer currentSession()  {
        Integer s =   session.get();
        if (s == null) {
            s = 0;
            session.set(s);         
        }
        s++;
        session.set(s);         
        return s;
    }
    
    /**
     * 获取当前线程中的Session
     * @return Session
     * @throws HibernateException
     */
    public static Integer currentSessionError()  {
        return s2++;
    }
}

 

 

 代码5

public class THibernate implements Runnable {

	@Override
	public void run() {
		while (true) {
			try {
				String currentThreadName = Thread.currentThread().getName();
				System.out.println("thread " + currentThreadName +"|tlocal:"+HibernateUtil.currentSession()+"|common:"+HibernateUtil.currentSessionError());
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		THibernate t=new THibernate();
		Thread t1 = new Thread(t, "t1");
		Thread t2 = new Thread(t, "t2");
		t1.start();
		t2.start();
	}
}

 

 

 

 运行结果:

thread t1|tlocal:1|common:0
thread t2|tlocal:1|common:1
thread t1|tlocal:2|common:2
thread t2|tlocal:2|common:3
thread t1|tlocal:3|common:4
thread t2|tlocal:3|common:5
thread t1|tlocal:4|common:6
thread t2|tlocal:4|common:7
thread t1|tlocal:5|common:8
thread t2|tlocal:5|common:9

 HibernateUtil是一个可供多线程访问的工具类,从运行结果来看ThreadLocal做到了变量的线程隔离,而普通的类变量无法做到这点。

 那我把代码4里的

public static Integer s2=0;

 改成

public Integer s2=0;

 不就也完成了ThreadLocal做的事情吗

但是,你的方法是static的,用到的变量也需要是static的,在这种情况下,还真的必须用ThreadLocal,才能做到变量的线程隔离.

 

 

 

 原创文章,转载请声名出处  http://spjich.iteye.com/blog/2264457