Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The best way to handle this is to "serialize" your tasks. You can do this with a message queue - a class that maintains a <code>Vector</code> of message objects (tasks) and runs code based on each message. The queue runs on a thread that processes each task (message) in series. You create a simple message class for the different tasks - read RMS etc. A message can be an <code>Integer</code> if you like that wraps a number. The operation of adding and retrieving messages is synchronized but the code than does the tasks is not and runs on a simple switch block. The benefit of serializing your tasks is you don't have to worry about concurrency. Here is some of the essential code from a class I use to do this. </p> <pre><code>class MessageQueue implements Runnable{ Vector messages; Thread myThread; volatile boolean stop; public void start() { stop=false; myThread=new Thread(this); myThread.start(); } // add message to queue - this is public public synchronized void addMessage(Message m) { messages.addElement(m); if(stop) { start(); } else { // wake the thread notify(); } } // get next message from queue - used by this thread private synchronized Message nextMessage() { if(stop) return null; if(messages.isEmpty()) { return null; } else { Message m=(Message)messages.firstElement(); messages.removeElementAt(0); return m; } } public void run() { while (!stop) { // make thread wait for messages if (messages.size() == 0) { synchronized (this) { try { wait(); } catch (Exception e) { } } } if (stop) { // catch a call to quit return; } processMessage(); } } } // all the tasks are in here private void processMessage() { Message m = nextMessage(); switch (m.getType()) { case Message.TASK1: // do stuff break; case Message.TASK2: // do other stuff break; case Message.TASK3: // do other other stuff break; default: //handle bad message } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload