Skip to content

Instantly share code, notes, and snippets.

@kjaquier
Created May 21, 2014 09:13
Show Gist options
  • Save kjaquier/c58d360c01b14ef343d9 to your computer and use it in GitHub Desktop.
Save kjaquier/c58d360c01b14ef343d9 to your computer and use it in GitHub Desktop.
Slave task that allows for asynchronous operations based on a FIFO queue.
import java.util.LinkedList;
/**
* Slave task that allows for asynchronous operations based on a FIFO queue.
*/
public class Async extends Thread {
private LinkedList<Runnable> tasks = new LinkedList<Runnable>();
private boolean stop = false;
/**
* Add an operation to execute. Will be executed when
* previously added operations are finished.
*
* @param task
* Callback that contains the operations to execute
*/
public synchronized void enqueue(Runnable task) {
tasks.add(task);
this.notify();
}
/**
* Returns the next operation to execute. Blocking if the queue is empty.
*/
private synchronized Runnable dequeue() {
if (tasks.isEmpty()) {
try {
this.wait();
} catch (InterruptedException e) {
}
}
return tasks.removeFirst();
}
/**
* Stops the task when all remaining operations in the queue
* are finished.
*/
public synchronized void close() {
stop = true;
}
@Override
public void run() {
boolean over = false;
while (!over) {
dequeue().run();
synchronized (this) {
over = stop && tasks.isEmpty();
}
}
}
/**
* Tests...
*/
public static void main(String[] args) {
Async a = new Async();
Async b = new Async();
b.start();
for (int i = 0; i < 10; i++) {
final int no = i;
a.enqueue(new Runnable() {
@Override
public void run() {
System.out.println("a) " + no);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
}
});
}
for (int i = 0; i < 10; i++) {
final int no = i;
b.enqueue(new Runnable() {
@Override
public void run() {
System.out.println("b) " + no);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
});
}
b.close();
a.start();
a.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment