Java Advanced Technology Chapter 5 - High Concurrency ThreadLocal Thread Local Variables

foreword

Foreword click here:
http://blog.csdn.net/wang7807564/article/details/79113195

ThreadLocal thread local variable

ThreadLocal is a thread-local variable that uses space for time, while synchronized uses time for space. For example, in hibernate, the session exists in ThreadLocal, avoiding the use of synchronized.
Shared variable values ​​between threads usually use volatile, so that the visibility of a variable between multiple threads can be achieved.
The reason why ThreadLocal is a thread-local variable means that for the same TheadLocal variable, for each different thread, it is unique by itself. It writes data by itself and can only be read by its own thread. No data is written, and the value read is null. For example:

static ThreadLocal<Object> tl = new ThreadLocal<>();

//实例化了一个名为tl的变量

write code:

                new Thread(()->{

                        try {

                                TimeUnit.SECONDS.sleep(2);

                        } catch (InterruptedException e) {

                                e.printStackTrace();

                        }

                        tl.set("t1");

                        System.out.println(tl.get());

                }).start();

                new Thread(()->{

                        try {

                                TimeUnit.SECONDS.sleep(1);

                        } catch (InterruptedException e) {

                                e.printStackTrace();

                        }

                        tl.set("t2");

                        System.out.println(tl.get());

                }).start();

        }

The output results are t2 and t1 respectively.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324714624&siteId=291194637