在java程序中,常用的有两种机制来解决多线程并发问题,一种是sychronized方式,通过锁机制,一个线程执行时,让另一个线程等待,是以时间换空间的方式来让多线程串行执行。而另外一种方式就是ThreadLocal方式,通过创建线程局部变量,以空间换时间的方式来让多线程并行执行。两种方式各有优劣,适用于不同的场景,要根据不同的业务场景来进行选择。
在spring的源码中,就使用了ThreadLocal来管理连接,在很多开源项目中,都经常使用ThreadLocal来控制多线程并发问题,因为它足够的简单,我们不需要关心是否有线程安全问题,因为变量是每个线程所特有的。我自己也写了一个小例子,仅供大家参考,来、证明一下ThreadLocal对多线程并发问题的控制。
package com.threadlocal;
/**
* ThreadLocal 线程局部变量
* @author 24572
*
*/
public class TestThreadLocal {
private static ThreadLocal<Integer> threadLocal=new ThreadLocal<Integer>(){
@Override
protected Integer initialValue() {
return 0;
}
};
public Integer getNext(){
threadLocal.set(threadLocal.get()+1);
return threadLocal.get();
}
public static void main(String[] args) {
TestThreadLocal testThreadLocal=new TestThreadLocal();
TestThread t1=new TestThread(testThreadLocal);
TestThread t2=new TestThread(testThreadLocal);
TestThread t3=new TestThread(testThreadLocal);
t1.start();
t2.start();
t3.start();
}
public static class TestThread extends Thread{
private TestThreadLocal testThreadLocal;
public TestThread(com.threadlocal.TestThreadLocal testThreadLocal) {
this.testThreadLocal = testThreadLocal;
}
@Override
public void run() {
for(int i=0;i<3;i++){
System.out.println("thread:"+Thread.currentThread().getName()+"next:"+testThreadLocal.getNext());
}
}
}
}
运行结果是:
thread:Thread-0next:1
thread:Thread-0next:2
thread:Thread-0next:3
thread:Thread-2next:1
thread:Thread-2next:2
thread:Thread-2next:3
thread:Thread-1next:1
thread:Thread-1next:2
thread:Thread-1next:3
很明显的可以看到,虽然我用的是同一个对象,但是每次都是打印的123,并没有引发线程安全问题。