Created
July 23, 2016 22:11
-
-
Save jeffypooo/4fdc44c146f1d16dae011a2d253efac4 to your computer and use it in GitHub Desktop.
Task Executor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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