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

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 运维知识 > Android >内容正文

Android

Android ThreadUtil 线程公共类,判断是否在主线程/ 子线程执行 相关操作

發(fā)布時(shí)間:2024/9/30 Android 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android ThreadUtil 线程公共类,判断是否在主线程/ 子线程执行 相关操作 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
前言:通常,我們寫(xiě)的公共的模塊給別人用,但是這個(gè)模塊又必須在特定的線程中執(zhí)行。

? ? ? ? 比如,一個(gè)加載網(wǎng)絡(luò)圖片的的方法,需要在子線程中執(zhí)行。

/*** 加載網(wǎng)絡(luò)圖片*/private void loadImage() {try {//用延時(shí)3秒操作來(lái)模擬網(wǎng)絡(luò)操作Thread.sleep( 3000 );} catch (InterruptedException e) {e.printStackTrace();}}

  但是其他的同事在使用的時(shí)候,可能一不小心就在主線程中執(zhí)行了 loadImage() 方法。這樣就勢(shì)必造成了界面卡頓。

? ? ? 為了避免這種情況,我們需要一個(gè)線程判斷的工具 ThreadUtil 來(lái)幫助我們處理。

  • 當(dāng)前線程是主線程,拋出異常,不去加載
  • 當(dāng)前線程是子線程,繼續(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() {//判斷是否在子線程。 子線程:繼續(xù)執(zhí)行 主線程:拋出異常ThreadUtil.assertBackgroundThread();try {//用延時(shí)3秒操作來(lái)模擬網(wǎng)絡(luò)操作Thread.sleep( 3000 );} catch (InterruptedException e) {e.printStackTrace();}}

 可以看到在 loadImage() 方法中多了一句: ThreadUtil.assertBackgroundThread();

? ?在?assertBackgroundThread() 方法里,判斷如果不是子線程就直接拋出?"YOu must call this method on a background thread"

? ? 正確的調(diào)用應(yīng)該是:在子線程中調(diào)用 loadImage() ,比如:

new Thread(new Runnable() {@Overridepublic void run() {loadImage();}}).start();

  

? ?總結(jié):

  • ThreadUitl 是參考圖片加載框架Glide寫(xiě)的 .
  • ThreadUtil.assertBackgroundThread(); ? 要求在子線程中執(zhí)行
  • ThreadUtil.assertMainThread() ; ? ? ? ? ? 要求在主線程運(yùn)行
  • 代碼示例已上傳到 github:?https://github.com/zyj1609wz/ZUtils

?

? ? ?

?

總結(jié)

以上是生活随笔為你收集整理的Android ThreadUtil 线程公共类,判断是否在主线程/ 子线程执行 相关操作的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

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