ThreadLocal使用实例
ThreadLocal为解决多线程程序的并发问题提供了一种新的思路。使用这个工具类可以很简洁地编写出优美的多线程程序,
- ThreadLocal并不是一个Thread,而是Thread的局部变量。
ThreadLocal是解决线程安全问题一个很好的思路, - 它通过为每个线程提供一个独立的变量副本解决了变量并发访问的冲突问题。
- 在很多情况下,ThreadLocal比直接使用synchronized同步机制解决线程安全问题更简单,更方便,且结果程序拥有更高的并发性。
ThreadLocal类接口很简单,只有4个方法,我们先来了解一下:
- Object get():获取该线程局部变量的值。
- void set(Object value):给该线程局部变量赋值。
- protected Object initialValue():返回该线程局部变量的初始值,该方法是一个protected的方法,
- 显然是为了让子类覆盖而设计的。
- public void remove():将当前线程局部变量的值删除。
示例1
public class test2 {
// ①通过匿名内部类覆盖ThreadLocal的initialValue()方法,指定初始值
private static ThreadLocal<Object> seqNum = new ThreadLocal<Object>() {
public Integer initialValue() {
return 0;
}
};
// ②获取下一个序列值
public int getNextNum() {
seqNum.set((Integer) seqNum.get() + 1);
return (Integer) seqNum.get();
}
public static void main(String[] args) {
test2 sn = new test2();
// ③ 3个线程共享sn,各自产生序列号
TestClient t1 = new TestClient(sn);
TestClient t2 = new TestClient(sn);
TestClient t3 = new TestClient(sn);
new Thread(t1).start();
new Thread(t2).start();
new Thread(t3).start();
}
}
class TestClient implements Runnable {
private test2 sn;
public TestClient(test2 sn) {
super();
this.sn = sn;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
// ④每个线程打出3个序列值
System.out.println("thread[" + Thread.currentThread().getName() + "] sn[" + sn.getNextNum() + "]");
}
}
}
thread[Thread-0] sn[1]
thread[Thread-1] sn[1]
thread[Thread-2] sn[1]
thread[Thread-1] sn[2]
thread[Thread-2] sn[2]
thread[Thread-0] sn[2]
thread[Thread-2] sn[3]
thread[Thread-1] sn[3]
thread[Thread-0] sn[3]
分析:
考察输出的结果信息,我们发现每个线程所产生的序号虽然都
- 共享同一个test2实例,
- 但它们并没有发生相互干扰的情况,而是各自产生独立的序列号,
- 这是因为我们通过ThreadLocal为每一个线程提供了单独的副本。
示例2:
// 代码清单3 TopicDao:非线程安全
public class TopicDao {
private Connection conn;// ①一个非线程安全的变量
public void addTopic(){
Statement stat = conn.createStatement();// ②引用非线程安全变量
}
}
/**
由于①处的conn是成员变量,因为addTopic()方法是非线程安全的,必须在使用时创建一个新TopicDao实例(非singleton)。下面使用ThreadLocal对conn这个非线程安全的“状态”进行改造:
**/
// 代码清单4 TopicDao:线程安全
import java.sql.Connection;
import java.sql.Statement;
public class TopicDao {
// ①使用ThreadLocal保存Connection变量
private static ThreadLocal<Connection> connThreadLocal = new ThreadLocal<Connection>();
public static Connection getConnection(){
// ②如果connThreadLocal没有本线程对应的Connection创建一个新的Connection,并将其保存到线程本地变量中。
return connThreadLocal.get();
}
public void addTopic() {
// ④从ThreadLocal中获取线程对应的Connection
Statement stat = getConnection().createStatement();
}
}
- 如果connThreadLocal没有 本线程对应的Connection创建一个新的Connection,
- 并将其保存到线程本地变量中。