标签:
简单的单线程队列 -- 工作的时候遇到劣质打印机。给打印机发消息,打印机就会打印,如果在打印机还在打印的时候,就
再发消息打印,就会出现消息丢失。所以需要给上一个任务一些处理的间隔时间.
单线程的消息队列示例
- package demo1;
-
- import java.util.LinkedList;
-
- public class Main {
-
-
-
- private static Thread thread;
- private static LinkedList<Runnable> list = new LinkedList<Runnable>();
-
- static int test = 0;
-
- public static void main(String[] args) {
-
- final long time = System.currentTimeMillis();
- for (int i = 0; i < 20; i++) {
-
- tastEvent(new Runnable() {
- public void run() {
-
-
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
-
- e.printStackTrace();
- }
-
- System.out
- .println("第"
- + (++test)
- + ("个任务 耗时:" + (System
- .currentTimeMillis() - time)));
- }
-
- });
- }
- }
-
- public static void tastEvent(Runnable r) {
- synchronized (list) {
- list.add(r);
- }
- if (thread == null) {
- thread = new Thread(run);
- thread.start();
- }
-
-
- }
-
- static Runnable run = new Runnable() {
-
- @Override
- public void run() {
-
- synchronized (list) {
-
- while (!list.isEmpty()) {
-
- list.poll().run();
- }
- thread = null;
- }
- }
- };
-
- }
工作的时候遇到非常大的并发的情况,比如机器1秒只支持1000的并发,但是1秒接收了4000的并发。服务器就会崩掉。
最好将并发放到队列中,按1000的并发吞吐量来处理,这就是异步队列应用。
一个工程交给一个人做,需要花费3个月,交给2个人做,需要2个人做需要2个月,需要3个人做需要1个月半.....100.人.....1000人,几年也完不成。
带上以上道理看待以下的代码
观察以下代码(复制到android工程下运行):最后耗时约1600毫秒 而使用android的AsyncTask类来改写这段代码只需要耗时约200
- final long timer=System.currentTimeMillis();
- count=0;
- final Handler h=new Handler();
- for(int k=0;k<100;k++){
- new Thread(){
- @Override
- public void run() {
-
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
-
- e.printStackTrace();
- }
- h.post(new Runnable() {
- @Override
- public void run() {
- Toast.makeText(getApplicationContext()," 耗时"+ (System.currentTimeMillis() - timer), 1).show();
- System.err.println("编号"+(count++)+"线程消耗了"+(System.currentTimeMillis()-timer));
- }
- });
- }
- }.start();
可见增加多线程不提高性能,反而因为系统在不同的线程之间切换降低效率。因此我们需要让线程有序执行任务
以下是异步多线程处理队列的demo
- package demo2;
-
- import demo2.Task.OnFinishListen;
-
- public class Main {
-
-
- public static void main(String[] args) {
-
-
- Task.setThreadMaxNum(3);
- for (int i = 0; i < 15; i++) {
- new Task() {
-
- @Override
- public Object obtainData(Task task, Object parameter)
- throws Exception {
-
- Thread.sleep(500);
- return task.taskID;
- }
-
- }
- .setOnFinishListen(new OnFinishListen() {
-
- @Override
- public void onFinish(Task task, Object data) {
-
- System.err.println("任务编号"+task.taskID+"任务完成");
- }
- })
- .setTaskID(i)
- .start();
- }
- }
-
- }
- package demo2;
-
- import java.util.HashMap;
-
- import java.util.Map;
- import java.util.Observable;
- import java.util.Observer;
-
- public abstract class Task<P,R> implements Runnable, Observer,TaskAction<P,R>{
-
-
-
-
-
- public static void setThreadMaxNum(int num) {
- TaskQueue.ThreadMaxNum = num<1?1:num>100?100:num;
- }
-
-
-
- public static enum TaskPriority {
- max, min;
- }
-
-
- protected final static Exception withoutException = new Exception(
- "The state is without");
-
-
- private static HashMap<String, Task> nameTasks;
-
- public static HashMap<String, Task> getNameTask() {
- if (nameTasks == null) {
- nameTasks = new HashMap<String, Task>();
- }
- return nameTasks;
-
- }
-
- public Task<P,R> setSingletonName(String singletonName) {
- this.singletonName = singletonName;
- return this;
- }
-
- public String getSingletonName() {
- return singletonName;
- }
-
- public interface OnStartListen {
- void onStart(Task t);
- }
-
- public interface OnProgressListen {
- void onProgress(Task task, int progress, Object data);
- }
-
- public static interface OnFinishListen<P,R> {
- void onFinish(Task<P,R> task, R data);
- }
-
- public interface OnSystemStartListen {
- void onSystemStart(Task task);
- }
-
- public interface OnSystemFinishListen {
- void OnSystemFinish(Task t, Object data);
- }
-
-
-
-
- protected P parameter;
-
- protected OnStartListen onStartListen;
-
- protected OnProgressListen onProgressListen;
-
- protected OnFinishListen<P,R> onFinishListen;
-
- protected OnSystemStartListen onSystemStartListen;
-
- protected OnSystemFinishListen onSystemFinishListen;
-
-
- protected R result;
-
- protected int taskID = -1;
-
-
- protected String singletonName;
-
-
- protected Object tag;
-
- protected Thread thread;
-
- protected int tryAgainCount = 1;
-
- protected int tryAgainTime = 1000;
-
-
-
-
- protected TaskPriority priority = TaskPriority.min;
-
-
- protected HashMap<String,Object> dataMap;
-
-
- protected Task() {
- }
-
-
-
-
- public static enum TaskStatus {
-
- untreated, wait,error, finsh, running, without;
- }
-
-
- TaskStatus status = TaskStatus.untreated;
-
- public void setWithout() {
- this.status = TaskStatus.without;
- }
-
- public void remove() {
- this.status = TaskStatus.without;
- }
-
- public TaskPriority getPriority() {
- return priority;
- }
-
- public void setPriority(TaskPriority priority) {
- this.priority = priority;
- }
-
-
-
-
- public void start() {
- if (this.priority == null)
- this.priority = TaskPriority.min;
-
- synchronized (TaskQueue.tasks_wait) {
- if (getSingletonName() != null
- && Task.getNameTask().get(this.getSingletonName()) != null) {
- this.setWithout();
- } else {
- Task.getNameTask().put(this.getSingletonName(), this);
-
- }
-
- switch (priority) {
- case min:
- TaskQueue.tasks_wait.remove(this);
- TaskQueue.tasks_wait.add(this);
- break;
- case max:
- TaskQueue.tasks_wait.remove(this);
- TaskQueue.tasks_wait.addFirst(this);
- break;
- default:
- break;
- }
-
- TaskQueue.serivesRun();
- }
-
- }
-
-
- public void start(TaskPriority priority) {
-
-
- this.priority = priority;
- status=TaskStatus.wait;
- start();
- }
-
-
-
- final void threadRun() {
- thread = new Thread(this);
- thread.start();
- }
-
-
- public void shutDownExecute(){};
-
- public R cacheData(P parameter){
- return result;};
-
-
- public final Object Execute() throws Exception {
-
- if (onStartListen != null)
- onStartListen.onStart(this);
-
-
- if (onSystemStartListen != null)
- onSystemStartListen.onSystemStart(this);
-
- status = TaskStatus.running;
-
-
- Exception exception = null;
-
- if ((result = cacheData(parameter)) == null) {
-
-
- for (int i = 0; i < tryAgainCount; i++) {
- try {
-
- if (status == TaskStatus.without) {
- break;
- }
- exception = null;
- result = obtainData(this, parameter);
- System.out.println("result=" + result);
- break;
- } catch (Exception e) {
-
- if ((exception = e) == withoutException) {
- break;
- }
- e.printStackTrace();
- try {
- Thread.sleep(tryAgainTime);
- } catch (Exception e1) {
-
- e1.printStackTrace();
- }
- }
- }
- }
-
- if (exception != null) {
- throw exception;
- }
-
-
-
- if (status != TaskStatus.without) {
-
- if (onFinishListen != null) {
-
- onFinishListen.onFinish(this, result);
- }
- ;
-
-
- }
- if (onSystemFinishListen != null) {
- onSystemFinishListen.OnSystemFinish(this, result);
- }
- status = TaskStatus.finsh;
- return result;
- }
-
- public abstract R obtainData(Task<P,R> task, P parameter)throws Exception;
-
- @Override
- public void update(Observable observable, Object data) {
-
- observable.deleteObserver(this);
-
- this.shutDownExecute();
- this.setWithout();
- if (this.thread != null) {
- this.thread.interrupt();
- }
-
- this.tryAgainCount = 0;
- };
-
- @Override
- public void run() {
-
- try {
- Execute();
- } catch (Exception e) {
- e.printStackTrace();
- status = TaskStatus.error;
-
-
-
-
- if (status != TaskStatus.without) {
-
- if (onFinishListen != null) {
-
- onFinishListen.onFinish(this, result);
- }
-
- }
- if (onSystemFinishListen != null) {
- onSystemFinishListen.OnSystemFinish(this, e);
- }
- }
-
-
- TaskQueue.getRunnable().notifyWaitingTask();
-
- }
-
-
-
- public Object getTag() {
- return tag;
- }
-
- public Task setTag(Object tag) {
- this.tag = tag;
- return this;
- }
-
- public Thread getThread() {
- return thread;
- }
-
- public TaskStatus getStatus() {
- return status;
- }
-
- public Object getParameter() {
- return parameter;
- }
-
- public Task setParameter(P parameter) {
- this.parameter = parameter;
- return this;
- }
-
- public OnStartListen getOnStartListen() {
- return onStartListen;
- }
-
- public Task setOnStartListen(OnStartListen onStartListen) {
- this.onStartListen = onStartListen;
- return this;
- }
-
- public OnProgressListen getOnProgressListen() {
- return onProgressListen;
- }
-
- public Task setOnProgressListen(OnProgressListen onProgressListen) {
- this.onProgressListen = onProgressListen;
- return this;
- }
-
- public OnFinishListen getOnFinishListen() {
- return onFinishListen;
- }
-
- public Task setOnFinishListen(OnFinishListen onFinishListen) {
- this.onFinishListen = onFinishListen;
- return this;
- }
-
- public OnSystemStartListen getOnSystemStartListen() {
- return onSystemStartListen;
- }
-
- public OnSystemFinishListen getOnSystemFinishListen() {
- return onSystemFinishListen;
- }
-
- public void setOnSystemFinishListen(
- OnSystemFinishListen onSystemFinishListen) {
- this.onSystemFinishListen = onSystemFinishListen;
- }
-
-
- public int getTaskID() {
- return taskID;
- }
-
- public Task setTaskID(int taskID) {
- this.taskID = taskID;
- return this;
- }
-
- public Object getResult() {
- return result;
- }
-
- public int getTryAgainCount() {
- return tryAgainCount;
- }
-
- public Task setTryAgainCount(int tryAgainCount) {
- this.tryAgainCount = tryAgainCount;
- return this;
- }
-
- public int getTryAgainTime() {
- return tryAgainTime;
- }
-
- private Task setTryAgainTime(int tryAgainTime) {
- this.tryAgainTime = tryAgainTime;
- return this;
- }
-
-
-
- public Object put(String key,Object value) {
- if(dataMap==null)
- {
- dataMap=new HashMap<String, Object>();
- }
- return dataMap.put(key, value);
- }
- public Object get(String key,Object value) {
- if(dataMap==null)
- {
- dataMap=new HashMap<String, Object>();
- }
- return dataMap.get(key);
- }
-
-
-
- }
Demo代码下载地址
版权声明:本文为博主原创文章,未经博主允许不得转载。
Java Design Demo -简单的队列-异步多任务队列(java android)
标签:
原文地址:http://www.cnblogs.com/Free-Thinker/p/4821404.html