1. Future模式
- 作用: 当任务执行时间很久,导致阻塞其它任务的执行,降低了系统的吞吐量。而Future则不阻塞任务的执行。
public interface FutureTask<T> {
T call();
}
public interface Future<T> {
T get() throws InterruptedException;
}
public class AsyncFuture<T> implements Future<T> {
private volatile boolean done = false;
private T result;
@Override
public T get() throws InterruptedException { synchronized (this) {
while (!done) {
this.wait();
}
}
return result;
}
public void done(T result) { synchronized (this) {
this.result = result;
this.done = true;
this.notifyAll();
}
}
}
public class FutureService {
public <T> Future<T> submit(final FutureTask<T> task) {
AsyncFuture<T> asyncFuture = new AsyncFuture<>();
new Thread(() -> {
T result = task.call();
asyncFuture.done(result);
}).start();
return asyncFuture;
}}
public class FutureDemo {
public static void main(String[] args) throws InterruptedException {
FutureService futureService = new FutureService();
Future<String> future = futureService.submit(() -> {
try {
Thread.sleep(5_000);
} catch (InterruptedException e) { e.printStackTrace();
}
return "Finish!";
});
System.out.println("================");
System.out.println(" do other thing......");
Thread.sleep(1_000);
System.out.println("result: " + future.get());
}
}
- 使用callBack方式
- 好处:可以根据传入的consumer, 任务处理完成了自动调用consumer方法。不需要我们再次去get数据。而可能造成的任务未完成时的等待。
public <T> Future<T> submit(final FutureTask<T> task, Consumer<T> consumer) {
AsyncFuture<T> asyncFuture = new AsyncFuture<>();
new Thread(() -> { T result = task.call();
asyncFuture.done(result);
consumer.accept(result);
}).start();
return asyncFuture;
}
测试:
Future<String> future = futureService.submit(() -> {
try {
Thread.sleep(5_000);
} catch (InterruptedException e) { e.printStackTrace();
}
return "Finish!";
}, System.out::println);