Demo Code Download Address
Simple single-threaded queues--bad printers are encountered at work. Send a message to the printer, the printer will print, if the printer is still printing,
If you send another message to print, you will receive a message loss. So you need to give the previous task some processing time interval.
Single-threaded Message Queuing example
Package demo1;
Import java.util.LinkedList;
public class Main {/** * @param args * * private static thread thread;
private static linkedlist<runnable> list = new linkedlist<runnable> ();
static int test = 0; public static void Main (string[] args) {//TODO auto-generated method stub final long time = System.currenttimemillis
(); for (int i = 0; i < i++) {tastevent, new Runnable () {public void run () {try {Thread.Sleep
(500);
catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace (); } System.out. println ("First" + (++test) + ("Task time consuming:" + (System. Currenttimemi
Llis ()-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 () {@Overridepublic void Run () {//TODO auto-generated Method stub synchronized (list) {while (!list.isempty ()) {//
New Thread (List.poll ()). Start ();
List.poll (). run ();
thread = NULL;
}
}
};
}
The work encountered a very large concurrency, such as the machine 1 seconds to support only 1000 concurrent, but 1 seconds received 4000 of the concurrency. The server will be blown off.
It is best to send and distribute to the queue, which is handled by 1000 concurrent throughput, which is the asynchronous queue application.
A project to a person to do, need to spend 3 months, to 2 people to do, need 2 people do need 2 months, need 3 people do need 1 months and a half ... 100. People ... 1000 people, and a few years will not finish.
With the above, see the following code
Look at the following code (running under Android): It takes about 1600 milliseconds to rewrite the code using Android's Asynctask class, which can take about 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 () {
//TODO auto-generated method Stub
try {
thread.sleep;
} catch (Interruptedexception e) {
//TODO auto-generated catch block< C13/>e.printstacktrace ();
}
H.post (New Runnable () {
@Override public
void Run () {Toast.maketext () (
getapplicationcontext (), "time-consuming" + ( System.currenttimemillis ()-timer), 1. Show ();
System.err.println ("number" + (count++) + thread Consumed + (System.currenttimemillis ()-timer));}}
);
Start ();
It can be seen that increasing multithreading does not improve performance, but because the system switches between different threads to reduce efficiency. So we need to have the thread perform the task in order.
The following is a demo of the asynchronous multithreaded processing queue
Package Demo2;
Import Demo2. Task.onfinishlisten;
public class Main {
/**
* @param args */public
static void Main (string[] args) {
//TODO Auto-generat Ed method Stub
Task.setthreadmaxnum (3);
for (int i = 0; i < i++) {
New task () {
@Override the public
Object obtaindata (Task task, Object Paramete R)
throws Exception {
//TODO auto-generated method stub
thread.sleep;
Return Task.taskid
}
}
. Setonfinishlisten (New Onfinishlisten () {
@Override public
void OnFinish (Task task, Object data) {
// TODO auto-generated Method Stub
System.err.println ("task number" +task.taskid+ "task Complete");
}
)
. 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>{//Set maximum number of tasks public static
void setthreadmaxnum (int num) {taskqueue.threadmaxnum = num<1?1:num>100?100:num;
public static enum Taskpriority {max, min;
/** Single example can be raised high performance/protected final static Exception withoutexception = new Exception ("The state is without");
Name Mapping 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);
/** Request Parameter */protected P parameter;
/** task Start monitoring/protected Onstartlisten Onstartlisten;
/** Task Progress monitoring/protected Onprogresslisten Onprogresslisten;
/** task complete monitoring/protected onfinishlisten<p,r> Onfinishlisten;
The/** task completes the monitoring in the queue/protected Onsystemstartlisten Onsystemstartlisten;
/** task in the queue to start monitoring/protected Onsystemfinishlisten Onsystemfinishlisten;
/** is used to send a message after the task is completed//** result/protected R results;
/** Task number marked */protected int taskID =-1;
/** Task Name//** Set whether this task name is a single example, in the case of a single instance, a new task cannot be added when a task with the same name has not been executed/protected String singletonname;
/** save an object */protected object tag; /** obtains the current reference of its own thread in the ThreadRun method * * ProtectedThread thread;
/** number/protected int tryagaincount = 1;
/** Heavy-interconnect/protected int tryagaintime = 1000;
/** Default Priority Low */protected taskpriority priority = Taskpriority.min;
protected hashmap<string,object> Datamap; Protected task () {}//Tasks status public static enum TaskStatus {//Unhandled error complete execution excluded untreated, wait,error, Finsh, R
Unning, without;
/** state */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;
/** Start thread */public void start () {if (this.priority = null) this.priority = Taskpriority.min; Synchronized (taskqueue.tasks_wait) {if (getsingletonname ()!= null && task.getnametask (). Get (This.getsin
Gletonname ())!= 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;
//Start this service taskqueue.serivesrun ();
}/** Start thread */public void Start (Taskpriority priority) {this.priority = priority;
status=taskstatus.wait;
Start ();
/** start thread/final void ThreadRun () {thread = new thread (this);
Thread.Start ();
//Break Execute method public void Shutdownexecute () {};
Public R cachedata (P parameter) {return result;}; Prohibit overridden public final Object Execute () throws Exception {//TODO auto-generated Method stub if (Onstartlisten!= nul
L) Onstartlisten.onstart (this);
Callback if (Onsystemstartlisten!= null) Onsystemstartlisten.onsystemstart (this) in the queue;
The state never handles changes for the process status = taskstatus.running; Gets the last error Exception Exception = null; Whether there is cached data if there is no if ((result = cachedata (parameter) = = NULL) {//Failed to redo the number for (int i = 0; i < Tryagaincount; i++
{try {///if state changes to exclusion then jump out of failure taskstatus.without if (status = =) {break;
} exception = null;
result = Obtaindata (this, parameter);
System.out.println ("result=" + result);
Break catch (Exception e) {//TODO auto-generated catch Block if (Exception = e) = = withoutexception) {Brea
K
} e.printstacktrace ();
try {thread.sleep (tryagaintime);
catch (Exception E1) {//TODO auto-generated catch block E1.printstacktrace ();
The IF (exception!= null) {Throw exception) is thrown if the last time it still fails; ///If the status changes to finish processing but does not notify if (status!= taskstatus.without) {if (Onfinishlisten!= null) {//complete listener and add results to main thread o
Nfinishlisten.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) {//Removal observation observable.deleteobserver (this);
Interrupt Stop Shutdown Connection this.shutdownexecute ();
This.setwithout ();
if (this.thread!= null) {this.thread.interrupt ();
///Error attempts 0 this.tryagaincount = 0;
};
@Override public void Run () {try {Execute ();
catch (Exception e) {e.printstacktrace ();
status = Taskstatus.error; If the state changes to finish processing but does not inform if (status!= taskstatus.without) {if (Onfinishlisten!= null) {///Add the result to the main thread onfi
Nishlisten.onfinish (this, result);
} if (Onsystemfinishlisten!= null) {Onsystemfinishlisten.onsystemfinish (this, e);
Taskqueue.getrunnable ()///recursive to avoid a new thread wakeup wait task. Notifywaitingtask (); Public Object Gettag () {REturn tag;
The 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;
The public Task setparameter (P parameter) {this.parameter = parameter;
return this;
Public Onstartlisten Getonstartlisten () {return onstartlisten;
The public Task Setonstartlisten (Onstartlisten onstartlisten) {this.onstartlisten = Onstartlisten;
return this;
Public Onprogresslisten Getonprogresslisten () {return onprogresslisten;
The public Task Setonprogresslisten (Onprogresslisten onprogresslisten) {this.onprogresslisten = Onprogresslisten;
return this;
Public Onfinishlisten Getonfinishlisten () {return onfinishlisten;
The 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 = OnS
Ystemfinishlisten;
public int GetTaskID () {return taskID;
The public Task settaskid (int taskID) {this.taskid = TaskID;
return this;
Public Object GetResult () {return result;
public int Gettryagaincount () {return tryagaincount;
The public Task settryagaincount (int tryagaincount) {this.tryagaincount = Tryagaincount;
return this;
public int Gettryagaintime () {return tryagaintime;
The private Task settryagaintime (int tryagaintime) {this.tryagaintime = Tryagaintime;
return this; The public Object is 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); }
}
Package Demo2;
Import java.util.AbstractCollection;
Import java.util.ArrayList;
Import java.util.Collections;
Import Java.util.Iterator;
Import java.util.LinkedList;
Import java.util.List;
Import Java.util.Queue;
Import Java.util.Random; Import Demo2.
Task.onsystemfinishlisten; Import Demo2.
Task.taskstatus;
public class Taskqueue implements Runnable, Onsystemfinishlisten {static String debug = "Taskqueue";
@SuppressWarnings ("unchecked")//in the waiting task queue static linkedlist<task> tasks_wait = new linkedlist<task> (); public static class Taskqueueexpection extends exception{taskqueueexpection (String detailmessage) {super (detailmess
Age);
TODO auto-generated Constructor stub};
The task being executed is static arraylist<task> tasks_running = new arraylist<task> ();
Whether the public static Boolean isrun=true continues to run;
Runnable guarantees thread safety private static taskqueue runnable = new Taskqueue ();;
Maximum number of threads static int threadmaxnum = 1; public static Taskqueue GetruNnable () {return runnable; ///If the queue thread is empty or stopped, reopen the public static void Serivesrun () {//TODO auto-generated method Stub Boolean Iscanseriver=fa
Lse
Synchronized (tasks_running) {iscanseriver=tasks_running.size () < Threadmaxnum;
} runnable.run (); //Get the number of tasks being performed public static int Getrunningtaskcount () {synchronized (taskqueue.tasks_running) {return Taskqueu
E.tasks_running.size ();
}///Set maximum task number public static void setthreadmaxnum (int num) {taskqueue.threadmaxnum = num<1?1:num>100?100:num; //thread Lock if the number of tasks waiting on the queue is not empty and the current thread number is less than the maximum number of threads public static Boolean Taskrun () {synchronized (tasks_wait) {synchronized (tasks_running)
{return!tasks_wait.isempty () && tasks_running.size () < Threadmaxnum;
Open new Thread public void run () {//thread lock if the number of tasks waiting on the queue is not empty and the current thread number is less than the maximum number of threads task NewTask;
while ((Newtask=getwaittingtask ())!=null) {System.err.println ("open a new thread to handle a new task, ID:" +newtask.gettaskid ()); NewtasK.setonsystemfinishlisten (runnable);
Newtask.threadrun ();
Newtask=null;
"}//recursive avoids new thread wakeup wait task but this scenario will cause java.lang.StackOverflowError void Notifywaitingtask () {task newtask;
while ((Newtask=getwaittingtask ())!=null) {System.err.println ("wake old thread to handle a new task, ID:" +newtask.gettaskid ());
Newtask.setonsystemfinishlisten (runnable);
Newtask.run ();
Newtask=null;
} Private Task Getwaittingtask () {task t=null; Test while (Isrun && taskrun ()) {//Add synchronized (tasks_wait) {//In a dynamic array in execution to get and remove the header of this list from the queue of the waiting task (first
Element) T = Tasks_wait.poll (); If h is empty, the object is fetched from the queue or the state of the task binding changes if (t = = NULL | | t.status = = taskstatus.without) {System.out.println ("task cancellation number" + t !=null?
String.valueof (T.gettaskid ()): "Empty Task");
Continue
} synchronized (tasks_running) {tasks_running.add (t);
} System.out.println ("The number of tasks being performed" + tasks_running.size () + "/upper Limit" + threadmaxnum);
return t;
} return t; } @OvErride public void Onsystemfinish (Task t, Object data) {//TODO auto-generated Method stub synchronized (Tasks_runni
NG) {//Removes the task Tasks_running.remove (t) from the dynamic array in process;
SYSTEM.OUT.PRINTLN ("Remove task taskid= in execution queue" + T.taskid);
Notifies the execution of subsequent unhandled tasks System.out.println ("The number of tasks being performed" + tasks_running.size () + "/upper Limit" + threadmaxnum);
Remove this name map if (t.getsingletonname ()!= null) {Task.getnametask (). Remove (T.getsingletonname ()); }
}
}
}
Demo Code Download Address