Skip to content

Instantly share code, notes, and snippets.

@Yi-Tseng
Created Mar 28, 2017
Embed
What would you like to do?
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
public class FooService {
private final Deque<SumTask> tasks = new ArrayDeque<SumTask>();
ThreadFactory threadFactory = Executors.defaultThreadFactory();
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2, threadFactory);
public FooService() {
executorService.scheduleAtFixedRate(new SumRobot(), 5, 1, TimeUnit.SECONDS);
}
public void sumAsync(int a, int b, Callback callback) {
SumTask task = new SumTask(a, b, callback);
synchronized (tasks) {
tasks.add(task);
}
}
public interface Callback {
void onSuccess(int result);
}
private class SumTask {
int a, b;
Callback callback;
public SumTask(int a, int b, Callback callback) {
this.a = a;
this.b = b;
this.callback = callback;
}
}
class SumRobot implements Runnable {
@Override
public void run() {
synchronized (tasks) {
if (!tasks.isEmpty()) {
SumTask task = tasks.removeFirst();
int result = task.a + task.b;
task.callback.onSuccess(result);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment