Android ThreadUtil 线程公共类,判断是否在主线程/ 子线程执行 相关操作
生活随笔
收集整理的這篇文章主要介紹了
Android ThreadUtil 线程公共类,判断是否在主线程/ 子线程执行 相关操作
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
前言:通常,我們寫(xiě)的公共的模塊給別人用,但是這個(gè)模塊又必須在特定的線(xiàn)程中執(zhí)行。
? ? ? ? 比如,一個(gè)加載網(wǎng)絡(luò)圖片的的方法,需要在子線(xiàn)程中執(zhí)行。
/*** 加載網(wǎng)絡(luò)圖片*/private void loadImage() {try {//用延時(shí)3秒操作來(lái)模擬網(wǎng)絡(luò)操作Thread.sleep( 3000 );} catch (InterruptedException e) {e.printStackTrace();}}但是其他的同事在使用的時(shí)候,可能一不小心就在主線(xiàn)程中執(zhí)行了 loadImage() 方法。這樣就勢(shì)必造成了界面卡頓。
? ? ? 為了避免這種情況,我們需要一個(gè)線(xiàn)程判斷的工具 ThreadUtil 來(lái)幫助我們處理。
- 當(dāng)前線(xiàn)程是主線(xiàn)程,拋出異常,不去加載
- 當(dāng)前線(xiàn)程是子線(xiàn)程,繼續(xù)執(zhí)行,完成加載
? ?
package com.app; import android.os.Looper;/*** Created by ${zyj} on 2016/6/7.*/ public class ThreadUtil {/*** Throws an {@link java.lang.IllegalArgumentException} if called on a thread other than the main thread.*/public static void assertMainThread() {if (!isOnMainThread()) {throw new IllegalArgumentException("You must call this method on the main thread");}}/*** Throws an {@link java.lang.IllegalArgumentException} if called on the main thread.*/public static void assertBackgroundThread() {if (!isOnBackgroundThread()) {throw new IllegalArgumentException("YOu must call this method on a background thread");}}/*** Returns {@code true} if called on the main thread, {@code false} otherwise.*/public static boolean isOnMainThread() {return Looper.myLooper() == Looper.getMainLooper();}/*** Returns {@code true} if called on the main thread, {@code false} otherwise.*/public static boolean isOnBackgroundThread() {return !isOnMainThread();}}然后我們把 loadImage() 修改一下,就成了
/*** 加載網(wǎng)絡(luò)圖片*/private void loadImage() {//判斷是否在子線(xiàn)程。 子線(xiàn)程:繼續(xù)執(zhí)行 主線(xiàn)程:拋出異常ThreadUtil.assertBackgroundThread();try {//用延時(shí)3秒操作來(lái)模擬網(wǎng)絡(luò)操作Thread.sleep( 3000 );} catch (InterruptedException e) {e.printStackTrace();}}可以看到在 loadImage() 方法中多了一句: ThreadUtil.assertBackgroundThread();
? ?在?assertBackgroundThread() 方法里,判斷如果不是子線(xiàn)程就直接拋出?"YOu must call this method on a background thread"
? ? 正確的調(diào)用應(yīng)該是:在子線(xiàn)程中調(diào)用 loadImage() ,比如:
new Thread(new Runnable() {@Overridepublic void run() {loadImage();}}).start();
? ?總結(jié):
- ThreadUitl 是參考圖片加載框架Glide寫(xiě)的 .
- ThreadUtil.assertBackgroundThread(); ? 要求在子線(xiàn)程中執(zhí)行
- ThreadUtil.assertMainThread() ; ? ? ? ? ? 要求在主線(xiàn)程運(yùn)行
- 代碼示例已上傳到 github:?https://github.com/zyj1609wz/ZUtils
?
? ? ?
?
總結(jié)
以上是生活随笔為你收集整理的Android ThreadUtil 线程公共类,判断是否在主线程/ 子线程执行 相关操作的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Android 视频播放器 VideoV
- 下一篇: Android http 的使用