Relatively simple, 3 classes.
1. Create a singleton thread pool to perform asynchronous tasks
<pre name= "code" class= "java" >package com.ferris.pool;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public class Ferrispoolmanager {private Executorservice service;private Ferrispoolmanager () {int num = Runtime.getruntime (). availableprocessors (); service = Executors.newfixedthreadpool (num * 2);} private static Ferrispoolmanager manager;public static Ferrispoolmanager getinstance () {if (manager = = null) {Synchronize D (Ferrispoolmanager.class) {if (manager = = null) {manager = new Ferrispoolmanager ();}}} Return manager;} public void AddTask (Runnable Runnable) {service.execute (Runnable);} public void Canceltask () {Service.shutdown ();}}
2. Define a task interface
Package Com.ferris.pool;public interface Ferristasklistem {public void get (); Run online thread public void update (); Run on the main thread (from where new is the thread, not necessarily the main line service, etc.)}
3. Task Execution Object
Package Com.ferris.pool;import Android.os.handler;import Android.os.message;public class Ferristask {private Ferristasklistem tasklistem;private Handler Handler = new Handler () {public void Handlemessage (Android.os.Message msg) {i F (tasklistem!=null) {tasklistem.update ();}};}; Public Ferristask (Ferristasklistem tasklistem) {this.tasklistem = Tasklistem;} public void Execute () {ferrispoolmanager.getinstance (). AddTask (New RunTask ());} public class RunTask implements Runnable {@Overridepublic void Run () {//TODO auto-generated method Stubif (Tasklistem!=nul L) {tasklistem.get ();} Message Message=message.obtain (); handler.sendmessage (message);}}}
4. How to use
Ferristask ferristask = new Ferristask (new Ferristasklistem () {@Overridepublic void update () { //main thread//TODO Auto-gene Rated method stubstring name = Thread.CurrentThread (). GetName (); System.out.print (name);} @Overridepublic void Get () {//ui thread//TODO auto-generated method stubstring name = Thread.CurrentThread (). GetName (); System.out.print (name);}); Ferristask.execute ();
Android asynchronous task code is short, simple asynchronous tool encapsulation, easy to perform asynchronous task