Skip to content

Instantly share code, notes, and snippets.

@jeffypooo
Created July 23, 2016 22:11
Show Gist options
  • Save jeffypooo/4fdc44c146f1d16dae011a2d253efac4 to your computer and use it in GitHub Desktop.
Save jeffypooo/4fdc44c146f1d16dae011a2d253efac4 to your computer and use it in GitHub Desktop.
Task Executor
public class WorkerThread extends Thread {
private final LinkedBlockingQueue<Runnable> tasks;
private final AtomicBoolean cancelled;
private final AtomicBoolean safeCanceled;
public WorkerThread() {
this.tasks = new LinkedBlockingQueue<>();
this.cancelled = new AtomicBoolean(false);
this.safeCanceled = new AtomicBoolean(false);
}
public boolean enqueueTask(Runnable task) {
return tasks.offer(task);
}
public void terminate() {
cancelled.getAndSet(true);
}
public void terminateSafely() {
safeCanceled.getAndSet(true);
}
@Override
public void run() {
while(!cancelled.get()) {
try {
//wait for queue to be empty first
if (tasks.size() == 0 && safeCanceled.get()) {
break;
}
Runnable task = tasks.take();
task.run();
} catch (InterruptedException e) {
if (cancelled.get()) {
break;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment