android 线程辅助处理类(用于在主线程和其他线程中执行逻辑)

48 篇文章 0 订阅
1 篇文章 0 订阅

 

// 1、在主线程执行逻辑—— 一般为涉及UI界面控件的处理逻辑
ThreadTool.RunInMainThread(new ThreadPram()
{
		@Override
		public void Function()
		{
			// TODO Auto-generated method stub
			// 在主线程执行逻辑
		}
});

// 2、在新的线程中执行逻辑—— 网络请求要求在非主线程中调用
ThreadTool.RunInCachedThread(new ThreadPram()
{
		@Override
		public void Function()
		{
			// TODO Auto-generated method stub
			// 在新的线程执行逻辑
		}
});


// 3、判断当前是否为主线程
bool isUi = isUiThread();


// 4、获取主Handler、当前Handler, Handler用于执行逻辑,或延时执行逻辑
getMainHandler()、getCurrentHandler()

Handler..postDelayed(new Runnable()
{
	@Override
	public void run()
	{
		param.Function();
	}
}, delayMillis);

package com.sc.tool;

import java.util.concurrent.Executors;
import android.os.Handler;
import android.os.Looper;


/** 线程辅助处理类,用于在主线程和其他线程中执行逻辑 */
public class ThreadTool
{
	// 调用示例
	public static void Example()
	{
		ThreadTool.RunInMainThread(new ThreadPram()
		{
			@Override
			public void Function()
			{
				// TODO Auto-generated method stub
				// 在主线程执行逻辑
			}
		});
	}
	
	// ---------------------------------------------
	
	/** 线程辅助处理类对象参数 */
	public static abstract class ThreadPram
	{
		/** 需要在线程中执行的逻辑 */
		public abstract void Function();
	}
	
	/** 在主线程执行Function —— UI界面相关控件逻辑需在主线程中执行 */
	public static void RunInMainThread(final ThreadPram param)
	{
		getMainHandler().post(new Runnable()
		{
			@Override
			public void run()
			{
				param.Function();
			}
		});
	}
	
	/** 在主线程中延时delayMillis毫秒,执行Function —— UI界面相关控件逻辑需在主线程中执行 */
	public static void RunInMainThread(final ThreadPram param, long delayMillis)
	{
		getMainHandler().postDelayed(new Runnable()
		{
			@Override
			public void run()
			{
				param.Function();
			}
		}, delayMillis);
	}
	
	/** 在其他线程执行Function —— 网络请求需在主线程之外的其他线程执行 */
	public static void RunInCachedThread(final ThreadPram param)
	{
		Executors.newCachedThreadPool().execute(new Runnable()
		{
			@Override
			public void run()
			{
				param.Function();
			}
		});
	}
	
	/** 当前线程是否为主线程 */
	public static boolean isUiThread()
	{
		return Thread.currentThread() == Looper.getMainLooper().getThread();
	}
	
	/** 获取主线程Handler */
	public static Handler getMainHandler()
	{
		return new Handler(Looper.getMainLooper());
	}
	
	/** 获取当前线程Handler */
	public static Handler getCurrentHandler()
	{
		return new Handler(Looper.myLooper());
	}
	
}

 
 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值