Skip to content

Instantly share code, notes, and snippets.

@Yi-Tseng
Created March 28, 2017 04:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yi-Tseng/a8161c1a1cc27031f7fc4b5e2f7eafe3 to your computer and use it in GitHub Desktop.
Save Yi-Tseng/a8161c1a1cc27031f7fc4b5e2f7eafe3 to your computer and use it in GitHub Desktop.
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