日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

另一鲜为人知的单例写法-ThreadLocal

發(fā)布時間:2025/4/5 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 另一鲜为人知的单例写法-ThreadLocal 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

另一鮮為人知的單例寫法-ThreadLocal

源代碼范例

當(dāng)我閱讀FocusFinder和Choreographer的時候,我發(fā)現(xiàn)這兩類的單例實現(xiàn)和我們尋經(jīng)常使用雙重檢查鎖非常不一樣。而是用來一個ThreadLocal。這個也能夠?qū)崿F(xiàn)單例啊,那這個與雙重檢查鎖實現(xiàn)的單例有什么差別呢?

1.FocusFinder

/*** The algorithm used for finding the next focusable view in a given direction* from a view that currently has focus.*/ public class FocusFinder {private static final ThreadLocal<FocusFinder> tlFocusFinder =new ThreadLocal<FocusFinder>() {@Overrideprotected FocusFinder initialValue() {return new FocusFinder();}};/*** Get the focus finder for this thread.*/public static FocusFinder getInstance() {return tlFocusFinder.get();}// enforce thread local accessprivate FocusFinder() {} }

2.Choreographer

public final class Choreographer {// Thread local storage for the choreographer.private static final ThreadLocal<Choreographer> sThreadInstance =new ThreadLocal<Choreographer>() {@Overrideprotected Choreographer initialValue() {Looper looper = Looper.myLooper();if (looper == null) {throw new IllegalStateException("The current thread must have a looper!");}return new Choreographer(looper);}};private Choreographer(Looper looper) {mLooper = looper;mHandler = new FrameHandler(looper);mDisplayEventReceiver = USE_VSYNC ?

new FrameDisplayEventReceiver(looper) : null; mLastFrameTimeNanos = Long.MIN_VALUE; mFrameIntervalNanos = (long)(1000000000 / getRefreshRate()); mCallbackQueues = new CallbackQueue[CALLBACK_LAST + 1]; for (int i = 0; i <= CALLBACK_LAST; i++) { mCallbackQueues[i] = new CallbackQueue(); } } /** * Gets the choreographer for the calling thread. Must be called from * a thread that already has a {@link android.os.Looper} associated with it. * * @return The choreographer for this thread. * @throws IllegalStateException if the thread does not have a looper. */ public static Choreographer getInstance() { return sThreadInstance.get(); } }

理論分析

ThreadLocal會為每個線程提供一個獨立的變量副本,從而隔離了多個線程對數(shù)據(jù)的訪問沖突。

對于多線程資源共享的問題,同步機制採用了“以時間換空間”的方式,而ThreadLocal採用了“以空間換時間”的方式。前者僅提供一份變量,讓不同的線程排隊訪問,而后者為每個線程都提供了一份變量。因此能夠同一時候訪問而互不影響。

public class ThreadLocal{/*** Provides the initial value of this variable for the current thread.* The default implementation returns {@code null}.** @return the initial value of the variable.*/protected T initialValue() {return null;}/*** Returns the value of this variable for the current thread. If an entry* doesn't yet exist for this variable on this thread, this method will* create an entry, populating the value with the result of* {@link #initialValue()}.** @return the current value of the variable for the calling thread.*/@SuppressWarnings("unchecked")public T get() {// Optimized for the fast path.Thread currentThread = Thread.currentThread();Values values = values(currentThread);if (values != null) {Object[] table = values.table;int index = hash & values.mask;if (this.reference == table[index]) {return (T) table[index + 1];}} else {values = initializeValues(currentThread);}return (T) values.getAfterMiss(this);}/*** Gets Values instance for this thread and variable type.*/Values values(Thread current) {return current.localValues;}/*** Sets the value of this variable for the current thread. If set to* {@code null}, the value will be set to null and the underlying entry will* still be present.** @param value the new value of the variable for the caller thread.*/public void set(T value) {Thread currentThread = Thread.currentThread();Values values = values(currentThread);if (values == null) {values = initializeValues(currentThread);}values.put(this, value);}}

實現(xiàn)步驟

//1.initialValue,創(chuàng)建ThreadLocal對象 //2.get(),獲取當(dāng)前線程里的values //3.假設(shè)不存在則初始化一個空的values //4.假設(shè)存在,則復(fù)用values

另一處經(jīng)典應(yīng)用

在Looper中使用ThreadLocal,使之每個Thread都有一個Looper與之相應(yīng).

public class Looper{// sThreadLocal.get() will return null unless you've called prepare().static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();/** Initialize the current thread as a looper.* This gives you a chance to create handlers that then reference* this looper, before actually starting the loop. Be sure to call* {@link #loop()} after calling this method, and end it by calling* {@link #quit()}.*/public static void prepare() {prepare(true);}private static void prepare(boolean quitAllowed) {if (sThreadLocal.get() != null) {throw new RuntimeException("Only one Looper may be created per thread");}sThreadLocal.set(new Looper(quitAllowed));} /*** Return the Looper object associated with the current thread. Returns* null if the calling thread is not associated with a Looper.*/public static @Nullable Looper myLooper() {return sThreadLocal.get();} }

自己也寫

public class Manager {private static final ThreadLocal<Manager> sManager = new ThreadLocal<Manager>() {@Overrideprotected Manager initialValue() {return new Manager();}};private Manager() {}public static Manager getInstance() {return sManager.get();} }

參考

  • 徹底理解ThreadLocal(http://blog.csdn.net/lufeng20/article/details/24314381)

總結(jié)

以上是生活随笔為你收集整理的另一鲜为人知的单例写法-ThreadLocal的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 久草网在线视频 | 久草热视频 | 亚洲精品在 | 国产又色又爽又黄 | 中文在线观看免费网站 | 天天插视频 | 色天天av| 少妇高清精品毛片在线视频 | 九色.com| 久久久久久无码精品大片 | 韩国久久精品 | 中文字幕dvd | 99热这里只有精品9 日韩综合在线 | 国产97色在线 | 国产精品yy | 小视频在线看 | 国产一区二区四区 | 国产1区二区 | 男女无遮挡免费视频 | 99日精品 | 久久精品欧美日韩精品 | av片网站 | 亚洲一区播放 | 久久男| 在线色av| 国产精品久久影院 | 午夜少妇视频 | 狠狠热免费视频 | 男人免费视频 | 免费看黄在线看 | 北条麻妃久久精品 | 神马午夜激情 | 手机在线毛片 | 秘密基地免费观看完整版中文 | 中文字幕在线观看第一页 | 激情视频网站在线观看 | 天天干天| 国产精品老女人 | 先锋影音av在线 | 97久久国产精品 | 欧美亚色 | 欧美性视频一区二区 | 国产黄色一级网站 | 亚洲人交配视频 | 久久成人免费电影 | 69精品人妻一区二区三区 | 丁香免费视频 | 69午夜| 操她视频在线观看 | 国产精品va在线 | 亚洲欧美综合在线观看 | 九九热精品免费视频 | 欧美乱妇高清无乱码 | 性涩av| 亚洲国产欧美日韩在线 | 97avcc | 可以免费看污视频的网站 | 蜜臀久久精品久久久久久酒店 | 美女搡bbb又爽又猛又黄www | 精品偷拍一区 | 爱爱免费网址 | 黄页网站视频在线观看 | 久久这里只有精品6 | 欧美一区二区免费视频 | 免费超碰在线观看 | www.av网址| 男人都懂的网址 | 亚洲精品国产精品国 | 少妇高潮毛片色欲ava片 | 白洁av| 五月婷婷天 | 欧美h网站 | 影视先锋av资源 | 成人动漫在线观看免费 | 老熟妇一区二区三区啪啪 | 亚洲人成影视 | 在办公室被c到呻吟的动态图 | 99久久综合国产精品二区 | 黄色午夜视频 | 免费网站在线观看黄色 | 上海贵妇尝试黑人洋吊 | 国产jjizz一区二区三区视频 | 黄色欧美大片 | 精品午夜一区二区 | 九九九九九精品 | 国产成人精品一区二区三区网站观看 | 高清不卡毛片 | 国产精品久久中文字幕 | 国产欧美精品一区二区色综合 | 国产人妻黑人一区二区三区 | 国产三级三级看三级 | 国产三级a| 日韩中文字幕网址 | ⅹxxxxhd亚洲日本hd老师 | 香蕉久久精品日日躁夜夜躁 | 另类小说av| 九九综合九九 | 黄色三级网络 | 午夜成人在线视频 |