多线程-ThreadLocal

2021-07-05 14:04

阅读:766

标签:except   线程安全   使用   stat   安全   rri   sys   ati   over   

1.threadLocal:本地线程变量,为每个线程提供副本,以此来保证线程安全。

2.性能:从并发的角度来说,如果并发量不是很大,加锁的方式会更好。并发量很大的情况下,使用threadlocal可以一定程度减小所竞争。

3.举个栗子:

public class test005_threadlocal {

    public static void main(String[] args) {

        ThreadLocal threadLocal = new ThreadLocal();//
        People p = new People();//

        //主线程
        threadLocal.set(new People(9));
        p.setAge(999);

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(0);
                    threadLocal.set(new People(111));
                    p.setAge(1);
                    System.out.println("t1-threadLocal:" + threadLocal.get().getAge());//输出的肯定是111
                    System.out.println("t1-p:" + p.getAge());//输出的不一定是1
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(0);
                    threadLocal.set(new People(222));
                    p.setAge(2);
                    System.out.println("t2-threadLocal:" + threadLocal.get().getAge());
                    System.out.println("t2-p:" + p.getAge());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(0);
                    threadLocal.set(new People(333));
                    p.setAge(3);
                    System.out.println("t3-threadLocal:" + threadLocal.get().getAge());
                    System.out.println("t3-p:" + p.getAge());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        System.out.println("main-threadLocal:" + threadLocal.get().getAge());
        System.out.println("main-p:" + p.getAge());
        System.out.println("----------------------------");
        t1.start();
        t2.start();
        t3.start();

    }
}

  看到了threadlocal来保证线程安全的本质了吗?代码中有,自己找。

多线程-ThreadLocal

标签:except   线程安全   使用   stat   安全   rri   sys   ati   over   

原文地址:https://www.cnblogs.com/mianduijifengba/p/9597622.html


评论


亲,登录后才可以留言!