ThreadLocal类与Synchonized对象锁的区别

来源:互联网 发布:h5活动报名系统源码 编辑:程序博客网 时间:2024/06/05 20:11
package com.brook.demo.threalocal;import java.util.Random;public class ThreadLocalDemo {    public static void main(String[] args) {        School school = new School();        Thread thread = new Thread(school);        thread.start();        Thread thread2 = new Thread(school);        thread2.start();    }}class School implements Runnable{    private ThreadLocal<Student> sutdentPool = new ThreadLocal<Student>();    @Override    public void run() {        // TODO Auto-generated method stub        accessStudent();    }    public void accessStudent() {        Student  stu= this.getSudent();         Random random = new Random();           int age = random.nextInt(100);           stu.setAge(age);         System.out.println("current thread first get age " + Thread.currentThread() + ":" + stu.getAge());         try {            Thread.sleep(1000);         } catch (InterruptedException e) {                // TODO Auto-generated catch block            e.printStackTrace();         }         System.out.println("current thread second get age "+ Thread.currentThread() + ":" + stu.getAge());      }    public Student getSudent() {        Student stu= sutdentPool.get();        if(stu==null) {            stu=new Student();            sutdentPool.set(stu);        }        return stu;    }}class Student {    private String name;    private int age;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }}

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

ThreadLocal和Synchonized都用于解决多线程并发访问。但是ThreadLocal与synchronized有本质的区别。synchronized是利用锁的机制,使变量或代码块在某一时该只能被一个线程访问。而ThreadLocal为每一个线程都提供了变量的副本,使得每个线程在某一时间访问到的并不是同一个对象,这样就隔离了多个线程对数据的数据共享。而Synchronized却正好相反,它用于在多个线程间通信时能够获得数据共享。

原创粉丝点击