您现在的位置是:首页 > 文章详情

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

日期:2017-05-15点击:539
前言:通常,我们写的公共的模块给别人用,但是这个模块又必须在特定的线程中执行。

        比如,一个加载网络图片的的方法,需要在子线程中执行。

 /** * 加载网络图片 */ private void loadImage() { try { //用延时3秒操作来模拟网络操作 Thread.sleep( 3000 ); } catch (InterruptedException e) { e.printStackTrace(); } } 

但是其他的同事在使用的时候,可能一不小心就在主线程中执行了 loadImage() 方法。这样就势必造成了界面卡顿。

      为了避免这种情况,我们需要一个线程判断的工具 ThreadUtil 来帮助我们处理。

  • 当前线程是主线程,抛出异常,不去加载
  • 当前线程是子线程,继续执行,完成加载

   

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() 修改一下,就成了

 /** * 加载网络图片 */ private void loadImage() { //判断是否在子线程。 子线程:继续执行 主线程:抛出异常 ThreadUtil.assertBackgroundThread(); try { //用延时3秒操作来模拟网络操作 Thread.sleep( 3000 ); } catch (InterruptedException e) { e.printStackTrace(); } } 

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

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

    正确的调用应该是:在子线程中调用 loadImage() ,比如:

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

   总结:

  • ThreadUitl 是参考图片加载框架Glide写的 .
  • ThreadUtil.assertBackgroundThread();   要求在子线程中执行
  • ThreadUtil.assertMainThread() ;           要求在主线程运行
  • 代码示例已上传到 github: https://github.com/zyj1609wz/ZUtils

 

     

 

原文链接:https://yq.aliyun.com/articles/303946
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章