转载:http://lighter.iteye.com/blog/145281
如果有看到spring的一些源码的同学都知道,ThreadLocal对象在spring几乎在每一个重要的类的都存在其身影。到底ThreadLocal是有什么用的呢,让我们来揭开其面纱吧。
假如某一个对象是非线程安全的,在多线程的环境下,对对象的访问则须采用synchronized或lock/unlock进行线程同步,采用这样的方法限制了并发的访问,会带来比较大的性能损失.当然,我们可以在无须同步的的情况下,来化解线程安全的问题---就是采用ThreadLocal.
其实可以把ThreadLocal看成一个线程的局部变量,我们可以通过ThreadLocal为每一个线程提供了单独的副本.
ThreadLocal会为每一个线程提供一个独立的变量副本,从而隔离了多个线程对数据的访问冲突.因为每一个线程都拥胡自己的变量副本,从而也就没有必要对该变量进行同步了.
ThreadLocal提供了线程安全的共享对象,在编写多线程代码的时候,可以把不安全的变量封装进ThreadLocal.
其实从另一个角度上看,对于多线程的资源共享的问题,同步机制采用了"以时间换空间"的方式,而ThreadLocal则采用了"以空间换时间"的方式。[注:这一句话来自 向同事借看的<<精通spring2.x企业开发详解>>一书第九章]
举一个例子,先说明一下各类的用途如下:
Log类是用来将程序的log记录存放在log.txt里面的,进行分配线程的工作
TSLog产生Log的类,实例由每个线程所拥有
ClientThread调用Log的线程
首先来看看Log类的写法:
public class Log {
private static final ThreadLocal tsLogCollection = new ThreadLocal();
// 加入一个log
public static void println(String s) {
getTSLog().println(s);
}
// 关闭log
public static void close() {
getTSLog().close();
}
// 取得线程特有的log,注意每一个线程都有一个副本的log,所以无论怎样调用TSLog的内容,都不会出现数据出错的现象
private static TSLog getTSLog() {
TSLog tsLog = (TSLog)tsLogCollection.get();
//如果线程是第一次呼叫,就建立新挡案并登陆log
if (tsLog == null) {
tsLog = new TSLog(Thread.currentThread().getName() + "-log.txt");
tsLogCollection.set(tsLog);
}
return tsLog;
}
}
再来看看最普通不过的TSLog类
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;
public class TSLog {
private PrintWriter writer = null;
// 初始化writer字段
public TSLog(String filename) {
try {
writer = new PrintWriter(new FileWriter(filename));
} catch (IOException e) {
e.printStackTrace();
}
}
// 加入一笔log
public void println(String s) {
writer.println(s);
}
// 关闭log
public void close() {
writer.println("==== End of log ====");
writer.close();
}
}
再写一个ClientThread类:
public class ClientThread extends Thread {
public ClientThread(String name) {
super(name);
}
public void run() {
System.out.println(getName() + " BEGIN");
for (int i = 0; i < 10; i++) {
Log.println("i = " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
Log.close();
System.out.println(getName() + " END");
}
}
简单的类的类如下:
public class Main {
public static void main(String[] args) {
new ClientThread("A").start();
new ClientThread("B").start();
new ClientThread("C").start();
}
}
会产生A_log.txt,B_log.txt,以及c_log.txt三个文件,每一个文件的内容都是为
[quote]main: i=1
main: i=2
....
main: i=10[/quote]
其实ThreadLocal的方法很简单的,只有一个set,get,remove,还有一个initialValue()等四个方法而已。
再来看一个例子:
public class SequenceNumber {
private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>(){
public Integer initialValue(){
return 0;
}
};
public int getNextNum(){
seqNum.set(seqNum.get()+1);
return seqNum.get();
}
public static void main(String[] args)
{
SequenceNumber sn = new SequenceNumber();
TestClient t1 = new TestClient(sn);
TestClient t2 = new TestClient(sn);
TestClient t3 = new TestClient(sn);
t1.start();
t2.start();
t3.start();
}
private static class TestClient extends Thread
{
private SequenceNumber sn;
public TestClient(SequenceNumber sn) {
this.sn = sn;
}
public void run()
{
for (int i = 0; i < 3; i++) {
System.out.println("thread["+Thread.currentThread().getName()+"] sn["+sn.getNextNum()+"]");
}
}
}
}
运行结果如下:
[quote]thread[Thread-2]sn[1]
thread[Thread-0]sn[1]
thread[Thread-1]sn[1]
thread[Thread-2]sn[2]
thread[Thread-0]sn[2]
thread[Thread-1]sn[2]
thread[Thread-2]sn[3]
thread[Thread-0]sn[3]
thread[Thread-1]sn[3][/quote]
从结果可以看出,ThreadLocal为每一个线程都提供了一个对象的副本
注:核心代码来源为<<Java多线程设计模式>>和向同事借看的<<精通spring2.x企业开发详解>>一书第九章