服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - JAVA教程 - Java 中ThreadLocal类详解

Java 中ThreadLocal类详解

2020-04-13 11:30赵杰A-124 JAVA教程

什么是ThreadLocal?顾名思义它是local variable(线程局部变量)。它的功用非常简单,就是为每一个使用该变量的线程都提供一个变量值的副本,是每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突。从线程的角

ThreadLocal类,代表一个线程局部变量,通过把数据放在ThreadLocal中,可以让每个线程创建一个该变量的副本。也可以看成是线程同步的另一种方式吧,通过为每个线程创建一个变量的线程本地副本,从而避免并发线程同时读写同一个变量资源时的冲突。

示例如下:

?
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
 
import com.sun.javafx.webkit.Accessor;
 
public class ThreadLocalTest {
 static class ThreadLocalVariableHolder {
  private static ThreadLocal<Integer> value = new ThreadLocal<Integer>() {
   private Random random = new Random();
   
   protected synchronized Integer initialValue() {
    return random.nextInt(10000);
   }
  };
  
  public static void increment() {
   value.set(value.get() + 1);
  }
  
  public static int get() {
   return value.get();
  }
 }
 
 static class Accessor implements Runnable{
  private final int id;
  
  public Accessor(int id) {
   this.id = id;
  }
  
  @Override
  public void run() {
   while (!Thread.currentThread().isInterrupted()) {
    ThreadLocalVariableHolder.increment();
    System.out.println(this);
    Thread.yield();
   }
  }
  
  @Override
  public String toString() {
   return "#" + id + ": " + ThreadLocalVariableHolder.get();
  }
  
 }
 
 public static void main(String[] args) {
  ExecutorService executorService = Executors.newCachedThreadPool();
  for (int i = 0; i < 5; i++) {
   executorService.execute(new Accessor(i));
  }
  try {
   TimeUnit.MICROSECONDS.sleep(1);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  executorService.shutdownNow();
 }
 
}

运行结果:

?
1
2
3
4
5
6
7
8
#1: 9685
#1: 9686
#2: 138
#2: 139
#2: 140
#2: 141
#0: 5255
。。。

由运行结果可知,各线程都用于各自的Local变量,并各自读写互不干扰。

ThreadLocal共提供了三个方法来操作,set,get和remove。

在Android 中的Looper,即使用了ThreadLocal来为每个线程都创建各自独立的Looper对象。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public final class Looper {
 private static final String TAG = "Looper";
 
 // sThreadLocal.get() will return null unless you've called prepare().
 static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
 
 private static void prepare(boolean quitAllowed) {
  if (sThreadLocal.get() != null) {
   throw new RuntimeException("Only one Looper may be created per thread");
  }
  sThreadLocal.set(new Looper(quitAllowed));
 }
 
 。。。
}

当某个线程需要自己的Looper及消息队列时,就调用Looper.prepare(),它会为线程创建属于线程的Looper对象及MessageQueue,并将Looper对象保存在ThreadLocal中。

延伸 · 阅读

精彩推荐