-
-
Save Yi-Tseng/a8161c1a1cc27031f7fc4b5e2f7eafe3 to your computer and use it in GitHub Desktop.
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
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