ThreadLocal 与 Synchronized 的区别

x33g5p2x  于2021-12-22 转载在 其他  
字(2.3k)|赞(0)|评价(0)|浏览(224)

一 使用 ThreadLocal 的代码

package threadLocal;

/**
* @className: ThreadLocalDemoWithThreadLocal
* @description: 线程隔离
* 在多线程并发的场景下,每个线程中的变量都是相互独立
* 线程A:设置(变量1) 获取(变量1)
* 线程B:设置(变量2) 获取(变量2)
* ThreadLocal:
* set():将变量绑定到当前线程中
* get():获取当前线程绑定的变量
* @date: 2021/12/22
* @author: cakin
*/
public class ThreadLocalDemoWithThreadLocal {
    ThreadLocal<String> t1 = new ThreadLocal<>();
    // 变量
    private String content;

    public String getContent() {
        return t1.get();
    }

    public void setContent(String content) {
        // 变量 content 绑定到当前线程
        t1.set(content);
    }

    public static void main(String[] args) {
        ThreadLocalDemoWithThreadLocal demo = new ThreadLocalDemoWithThreadLocal();

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                // 每个线程:存一个变量,过一会,取出这个变量
                demo.setContent(Thread.currentThread().getName() + "的数据");
                System.out.println(Thread.currentThread().getName() + "--->" + demo.getContent());
            }).start();
        }
    }
}

二 使用 synchronized 的代码

package threadLocal;

/**
* @className: ThreadLocalDemoWithSyncronized
* @description: 使用 Syncronized 实现线程变量隔离
* @date: 2021/12/22
* @author: cakin
*/
public class ThreadLocalDemoWithSyncronized {
    // 变量
    private String content;

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public static void main(String[] args) {
        ThreadLocalDemoWithSyncronized demo = new ThreadLocalDemoWithSyncronized();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                synchronized (ThreadLocalDemoWithSyncronized.class) {
                    // 每个线程:存一个变量,过一会,取出这个变量
                    demo.setContent(Thread.currentThread().getName() + "的数据");
                    System.out.println(Thread.currentThread().getName() + "--->" + demo.getContent());
                }
            }).start();
        }
    }
}

三 测试结果

两者的测试结果都是预期,测试结果如下。

Thread-2--->Thread-2的数据
Thread-9--->Thread-9的数据
Thread-8--->Thread-8的数据
Thread-5--->Thread-5的数据
Thread-4--->Thread-4的数据
Thread-0--->Thread-0的数据
Thread-1--->Thread-1的数据
Thread-7--->Thread-7的数据
Thread-6--->Thread-6的数据
Thread-3--->Thread-3的数据

虽然使用 ThreadLocal  和 synchronized  都能解决问题,但是使用 ThreadLocal 更为合适,因为这样可以使用程序拥有更高的并发性。

四 区别

虽然 ThreadLocal 模式和 synchronized 关键字都用于处理多线程并发访问变量的问题,不过两者处理问题的角度和思路不同。

| <br> | <br>synchronized <br> | <br>ThreadLocal <br> |
| <br>原理<br> | <br>同步机制采用“以时间换空间”的方式,只提供了一份变量,让不同的线程排队访问。<br> | <br>采用“以空间换时间的方式,为每一个线程都提供了一份变量的副本,从而实现同时访问而相互不干扰”<br> |
| <br>侧重点<br> | <br>多线程之间访问资源的同步。<br> | <br>多线程中让每个线程之间的数据相互隔离。<br> |

五 参考

由浅入深,全面解析ThreadLocal_LeslieGuGu的博客-CSDN博客

相关文章