ThreadLocal与synchronized多线程并发访问区别2.docVIP

ThreadLocal与synchronized多线程并发访问区别2.doc

  1. 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
  2. 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  3. 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
  4. 4、该文档为VIP文档,如果想要下载,成为VIP会员后,下载免费。
  5. 5、成为VIP后,下载本文档将扣除1次下载权益。下载后,不支持退款、换文档。如有疑问请联系我们
  6. 6、成为VIP后,您将拥有八大权益,权益包括:VIP文档下载权益、阅读免打扰、文档格式转换、高级专利检索、专属身份标志、高级客服、多端互通、版权登记。
  7. 7、VIP文档为合作方或网友上传,每下载1次, 网站将根据用户上传文档的质量评分、类型等,对文档贡献者给予高额补贴、流量扶持。如果你也想贡献VIP文档。上传文档
查看更多
ThreadLocal与synchronized多线程并发访问区别2

由上面可以知道,使用同步是非常复杂的。并且同步会带来性能的降低。Java提供了另外的一种方式,通过ThreadLocal可以很容易的编写多线程程序。从字面上理解,很容易会把ThreadLocal误解为一个线程的本地变量。其它ThreadLocal并不是代表当前线程,ThreadLocal其实是采用哈希表的方式来为每个线程都提供一个变量的副本。从而保证各个线程间数据安全。每个线程的数据不会被另外线程访问和破坏。 我们把第一个例子用ThreadLocal来实现,但是我们需要些许改变。 Student并不是一个私有变量了,而是需要封装在一个ThreadLocal对象中去。调用ThreadLocal的set方法,ThreadLocal会为每一个线程都保持一份Student变量的副本。所以对student的读取操作都是通过ThreadLocal来进行的。 Java代码 protected Student getStudent() { ?? ???? Student student = (Student)studentLocal.get(); ?? ????if(student == null) { ?? ???????? student = new Student(); ?? ???????? studentLocal.set(student); ?? ???? } ?? ????return student; ?? } ?? ?? protected void setStudent(Student student) { ?? ???? studentLocal.set(student); ?? }?? accessStudent()方法需要做一些改变。通过调用getStudent()方法来获得当前线程的Student变量,如果当前线程不存在一个Student变量,getStudent方法会创建一个新的Student变量,并设置在当前线程中。 ??? Student student = getStudent(); ??? student.setAge(age); accessStudent()方法中无需要任何同步代码。 完整的代码清单如下: TreadLocalDemo.java Java代码 public class TreadLocalDemo implements Runnable { ?? ???private final static?? ThreadLocal studentLocal = new ThreadLocal(); ?? ??? ?? ???public static void main(String[] agrs) { ?? ??????? TreadLocalDemo td = new TreadLocalDemo(); ?? ????????? Thread t1 = new Thread(td,a); ?? ????????? Thread t2 = new Thread(td,b); ?? ???????? ?? ???????? t1.start(); ?? ???????? t2.start(); ?? ??????? ?? ??????? ?? ?? ?? ?????? } ?? ??? ?? ????/* (non-Javadoc) ????? * @see java.lang.Runnable#run() ????? */?? ????public void run() { ?? ????????? accessStudent(); ?? ???? } ?? ?? ????public??void?? accessStudent() { ?? ???????? ?? ???????? String currentThreadName = Thread.currentThread().getName(); ?? ???????? System.out.println(currentThreadName+ is running!); ?? ???????? Random random = new Random(); ?? ????????int age = random.nextInt(100); ?? ???????? System.out.println(thread +currentThreadName + set age to:+age); ?? ???????? Student student = getStudent(); ?? ???????? student.setAge(ag

文档评论(0)

xy88118 + 关注
实名认证
文档贡献者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档