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); }
时间: 2024-11-08 08:58:06