• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

实例讲解Java并发编程之ThreadLocal类

java 搞代码 4年前 (2022-01-05) 59次浏览 已收录 0个评论

这篇文章主要介绍了实例讲解Java并发编程之ThreadLocal类,本文给出了模拟ThreadLocal、实用ThreadLocal等代码实例,需要的朋友可以参考下

ThreadLocal类可以理解为ThreadLocalVariable(线程局部变量),提供了get与set等访问接口或方法,这些方法为每个使用该变量的线程都存有一份独立的副本,因此get总是返回当来源gao($daima.com搞@代@#码(网前执行线程在调用set时设置的最新值。可以将ThreadLocal视为 包含了Map对象,保存了特定于该线程的值。

概括起来说,对于多线程资源共享的问题,同步机制采用了“以时间换空间”的方式,而ThreadLocal采用了“以空间换时间”的方式。前者仅提供一份变量,让不同的线程排队访问,而后者为每一个线程都提供了一份变量,因此可以同时访问而互不影响。

模拟ThreadLocal

代码如下:
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
 
public class SimpleThreadLocal {
 private Map valueMap = Collections
   .synchronizedMap(new HashMap());
 
 public void set(T newValue) {
  valueMap.put(Thread.currentThread(), newValue); // ①键为线程对象,值为本线程的变量副本
 }
 
 public T get() {
  Thread currentThread = Thread.currentThread();
  T o = valueMap.get(currentThread); // ②返回本线程对应的变量
  if (o == null && !valueMap.containsKey(currentThread)) { // ③如果在Map中不存在,放到Map中保存起来。
   o = initialValue();
   valueMap.put(currentThread, o);
  }
  return o;
 }
 
 public void remove() {
  valueMap.remove(Thread.currentThread());
 }
 
 protected T initialValue() {
  return null;
 }
}

实用ThreadLocal

代码如下:
class Count {
 private SimpleThreadLocal count = new SimpleThreadLocal() {
  @Override
  protected Integer initialValue() {
   return 0;
  }
 };
 
 public Integer increase() {
  count.set(count.get() + 1);
  return count.get();
 }
 
}
 
class TestThread implements Runnable {
 private Count count;
 
 public TestThread(Count count) {
  this.count = count;
 }
 
 @Override
 public void run() {
  // TODO Auto-generated method stub
  for (int i = 1; i <= 3; i++) {
   System.out.println(Thread.currentThread().getName() + “\t” + i
     + “th\t” + count.increase());
  }
 }
}
 
public class TestThreadLocal {
 public static void main(String[] args) {
  Count count = new Count();
  Thread t1 = new Thread(new TestThread(count));
  Thread t2 = new Thread(new TestThread(count));
  Thread t3 = new Thread(new TestThread(count));
  Thread t4 = new Thread(new TestThread(count));
  t1.start();
  t2.start();
  t3.start();
  t4.start();
 }
}

输出

代码如下:
Thread-0    1th    1
Thread-0    2th    2
Thread-0    3th    3
Thread-3    1th    1
Thread-1    1th    1
Thread-1    2th    2
Thread-2    1th    1
Thread-1    3th    3
Thread-3    2th    2
Thread-3    3th    3
Thread-2    2th    2
Thread-2    3th    3

以上就是实例讲解Java并发编程之ThreadLocal类的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:实例讲解Java并发编程之ThreadLocal类
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址