异步任务队列封装

DaemonTask.java

package com.dqyx.wzcl.util;

public abstract class DaemonTask {

    /**
     * 任务执行方法。
     */
    public abstract void execute();

}
View Code

DaemonTaskRunner.java

 1 package com.dqyx.wzcl.util;
 2 
 3 import java.util.LinkedList;
 4 
 5 import android.util.Log;
 6 
 7 public class DaemonTaskRunner implements Runnable
 8 {
 9     private volatile boolean runFlag = true; 
10 
11     /**
12      * 异步任务队列
13      */
14     protected LinkedList<DaemonTask> taskList = new LinkedList<DaemonTask>();
15 
16     public DaemonTaskRunner()
17     {
18             init();
19     }
20 
21     /**
22      * 初始化方法,启动后台异步任务管理器
23      */
24     public void init()
25     {
26         this.runFlag = true;
27         Thread thread = new Thread(this);
28         thread.start();
29     }
30     
31     public void finish()
32     {
33         synchronized (this.taskList)
34         {
35             this.runFlag = false;
36             this.taskList.clear();
37             this.taskList.notify();
38         }
39     }
40 
41     /**
42      * 线程执行方法,覆盖Runnable的方法 检查任务队列里面是否有任务,如果有就执行;如果没有就进入休眠状态。
43      */
44     public void run()
45     {
46         while (this.runFlag)
47         {
48             // 从taskList队尾取出任务并执行
49             try
50             {
51                 DaemonTask task = null;
52                 synchronized (this.taskList)
53                 {
54                     if (this.taskList.size() != 0)
55                     {
56                         task = this.taskList.removeLast();
57                     }
58                     else
59                     {
60                         // 如果没有任务,就休眠。
61                         this.taskList.wait();
62                     }
63                 }
64                 if (task != null)
65                 {
66                     task.execute();
67                 }
68             }
69             catch (Exception e)
70             {
71                 Log.e("DaemonTaskRunner", "DaemonTaskRunner get and run task failed!",e);
72             }
73         }
74     }
75 
76     /**
77      * 添加一个异步任务到执行队列 添加后唤醒执行线程
78      * 
79      * @param task
80      *            DaemonTask
81      */
82     public void addTask(DaemonTask task)
83     {
84         synchronized (this.taskList)
85         {
86             this.taskList.addFirst(task);
87             this.taskList.notifyAll();
88         }
89     }
90 }
View Code

此外还可以将Handler与具体的excute()方法进行封装,写成一个 整体的框架,这里只是实现了核心部分,将任务添加到队列中。

天生我才必有用,千金散去还复来!
原文地址:https://www.cnblogs.com/Jack-Lu/p/3154128.html