Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package util;
- import java.util.function.Supplier;
- /**
- * Created by Roman on 04.11.14.
- */
- public class AsyncFunction<T> {
- private Thread thread;
- private T result;
- private boolean isStarted = false;
- public AsyncFunction(Supplier<T> supplier) {
- this(supplier, true);
- }
- public AsyncFunction(Supplier<T> supplier, boolean autoStart) {
- thread = new Thread(() -> result = supplier.get());
- if (autoStart) {
- thread.start();
- isStarted = true;
- }
- }
- public void start() {
- if (!isStarted) {
- thread.start();
- } else {
- throw new RuntimeException("Thread already started");
- }
- }
- public T getResult() {
- if (!isStarted) {
- throw new RuntimeException("Thread not started");
- }
- try {
- thread.join();
- thread = null;
- return result;
- } catch (InterruptedException e) {
- throw new RuntimeException("Interrupted by InterruptedException", e);
- }
- }
- public static<T> AsyncFunction<T> start(Supplier<T> supplier) {
- return new AsyncFunction<>(supplier, true);
- }
- public static<T> AsyncFunction<T> wait(Supplier<T> supplier) {
- return new AsyncFunction<>(supplier, false);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement