首页 > 移动平台 > 详细

无聊写个android的GCDのdispatch_async

时间:2015-08-21 15:59:39      阅读:329      评论:0      收藏:0      [点我收藏+]

    Block

public interface Block
{

	/**
	 * 
	 * 需要执行的任务
	 * 
	 * @return Object 执行的结果
	 */
	void IBuild();


	
}


    GCD

/**
 * GCD of Android
 * 
 * @author fred don
 *
 */
public class GCD
{

	public static String dispatch_get_main_queue()
	{
		return "main";
	}
	/**
	 * 1 x后台 运行
	 * 
	 * @author fred don
	 * @param threadName
	 *            [main UI线程运行 ,others /后台 运行]
	 * @param block
	 */
	public static void dispatch_async(String threadName, final Block block)
	{
		if ("main".equals(threadName))
		{
			handler.post(new Runnable()
			{
				@Override
				public void run()
				{
					if (block != null)
					{
						block.IBuild();
					}
				}
			});
		}
		else
		{
			Thread t = new Thread(new Runnable()
			{
				@Override
				public void run()
				{
					if (block != null)
					{
						block.IBuild();
					}
				}
			});
			t.setName(threadName);
			t.start();
		}
	}
	
 
	
	
	static Handler handler=new Handler();
}


用法

//后台线程
GCD.dispatch_async("back", new Block()
{
	
	@Override
	public void IBuild()
	{
		println(Thread.currentThread().getName());
		GCD.dispatch_async("main", new Block()
		{
			
			@Override
			public void IBuild()
			{
				println(Thread.currentThread().getName());
				
			}

		});
	}

});
//UI线程
GCD.dispatch_async("main", new Block()
{
	

	@Override
	public void IBuild()
	{
		println(Thread.currentThread().getName());
		
	}

});
		
public static void println(String s){
		Log.i("GCDTester", s);
	}


无聊写个android的GCDのdispatch_async

原文:http://my.oschina.net/u/1388778/blog/495442

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!