總結:Java的Stack嚴格意義來說並不能說是Stack,因為它通過直接繼承Vector類,繼承了Vector所有的公有方法,它是一個擁有所有Vector容器方法的棧! @SuppressWarnings 該批註的作用是給編譯器一條指令,告訴它對被批註的代碼元素內部的某些警告保持靜默。 | all ...
轉自:
http://www.java265.com/JavaCourse/202205/3370.html
下文筆者講述java中ThreadLocal的詳解說明,如下所示:
ThreadLocal簡介
ThreadLocal的功能:
用於創建線程局部變數的類
----------------------------------------------------------------------------
我們都知道我們創建的變數,可以被任何一個線程訪問和修改
但是當我們使用ThreadLocal創建的變數只能被當前線程訪問,其他線程無法訪問和修改
-----------------------------------------------------------------------------
ThreaLocal用法示例
ThreadLocal定義: ThreadLocal<String> threadLocalInfo = new ThreadLocal<>(); set方法 threadLocalInfo.set("java265.com"); get方法 threadLocalInfo.get(); 完整的示例 private void testThreadLocal() { Thread t = new Thread() { ThreadLocal<String> threadLocalInfo = new ThreadLocal<>(); @Override public void run() { super.run(); threadLocalInfo.set("java265.com--我最愛的網站"); threadLocalInfo.get(); } }; t.start(); }
ThreadLocal初始值--設置方法
ThreadLocal設置預設的get初始值
需要重寫initialValue方法
例: ThreadLocal<String> mThreadLocal = new ThreadLocal<String>() { @Override protected String initialValue() { return Thread.currentThread().getName(); } };
ThreadLocal的set方法原理說明
set方法源碼: public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); } getMap: ThreadLocalMap getMap(Thread t) { return t.threadLocals; } class Thread implements Runnable { ThreadLocal.ThreadLocalMap threadLocals = null; } 當一開始設置,即ThreadLocalMap對象未創建 則新建ThreadLocalMap對象,並設置初始值 void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); }
ThreadLocal導致記憶體泄露的原因說明
ThreadLocal實例被線程的ThreadLocalMap實例持有,也可以看成被線程持有。 當我們使用了線程池,由於之前的線程實例處理完之後出於復用的目的依然存活 即ThreadLocal設定的值被持有,才會導致記憶體泄露 ThreadLocal並不會產生記憶體泄露 因為ThreadLocalMap在選擇key的時候 並不是直接選擇ThreadLocal實例 而是ThreadLocal實例的弱引用。
static class ThreadLocalMap { /** * The entries in this hash map extend WeakReference, using * its main ref field as the key (which is always a * ThreadLocal object). Note that null keys (i.e. entry.get() * == null) mean that the key is no longer referenced, so the * entry can be expunged from table. Such entries are referred to * as "stale entries" in the code that follows. */ static class Entry extends WeakReference<ThreadLocal<?>> { /** The value associated with this ThreadLocal. */ Object value; Entry(ThreadLocal<?> k, Object v) { super(k); value = v; } } }
ThreadLocal使用場景
如:tractional 一個資料庫連接,在一個線程中只此一份,所以可使用ThreadLocal實現線程間變數共用