JavaBasic-ThreadLocal

ThreadLocal

  • ThreadLocal和线程同步机制都是为了解决多线程中相同变量的访问冲突问题。
  • 同步机制中,通过对象的锁机制保证同一时间只有一个线程访问变量。这个时候该变量是多个线程共享的。
  • ThreadLocal中,会为每一个线程提供一个独立的变量副本,从而隔离了多个线程对数据的访问冲突。
  • Demo1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* Created by Neko on 2017/11/9.
*/
public class ThreadL1 {
//通过匿名内部类覆盖ThreadLocal的initialValue()方法,指定初始值
private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>(){
public Integer initialValue(){
return 0;
}
};

//获取下一个序列值
public int getNextNum(){
System.out.println("____"+seqNum.get());
seqNum.set(seqNum.get()+1);
return seqNum.get();
}

public static void main(String[] args) {
ThreadL1 tl = new ThreadL1();
//三个线程共享tl,各自产生序列号
TestClient t1 = new TestClient(tl);
TestClient t2 = new TestClient(tl);
TestClient t3 = new TestClient(tl);

t1.start();
t2.start();
t3.start();
}

private static class TestClient extends Thread{
private ThreadL1 tl;
public TestClient(ThreadL1 tl){
this.tl = tl;
}

public void run(){
for (int i = 0; i<3 ;i++){
//每个线程打出3个序列值
//currentThread()获取当前运行的线程对象
System.out.println("Thread["+Thread.currentThread().getName()+"]--->tl["+tl.getNextNum()+"]");
}
}
}
}
  • Demo2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Created by Neko on 2017/11/9.
*/
public class ThreadL2 {

private Connection conn;//一个非线程安全的变量

public void addTopic1() throws SQLException{
Statement statement = conn.createStatement();//引用非线程安全变量
}

//--------------------->使用ThreadLocal这个connection这个非线程安全进行改造

public static ThreadLocal<Connection> connThreadLocal = new ThreadLocal<Connection>();

public static Connection getConnection(){
//如果connThreadLocal没有本线程对应的Connection创建一个新的Connection
//并将其保存到线程本地变量中
if(connThreadLocal.get() == null){
Connection conn = getConnection();
connThreadLocal.set(conn);
return conn;
} else {
return connThreadLocal.get();//直接返回本地变量
}
}

public void addTopic() throws SQLException{
//从Threadlocal中获取线程对应的Connection
Statement statement2 = getConnection().createStatement();

}
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×