多线程future设计械
package com.thread.ch8;public class AsynFuture<T> implements Future<T> {
public volatile boolean done = false;
private T result;
public void done(T result){
synchronized (this){
this.done = true;
this.result = result;
this.notifyAll();
}
}
@Override
public T get() throws InterruptedException {
synchronized (this){
while (!done){
this.wait();
}
return null;
}
}
}
//------------------------
public interface Future<T> {
T get() throws InterruptedException;
}
package com.thread.ch8;
/**
* 具体做事的
* @param <T>
*/
public interface FutureTask<T> {
T call();
}
package com.thread.ch8;
public class FutureTaskImpl<T> implements FutureTask {
@Override
public String call() {
try {
Thread.sleep(10000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "FINISH";
}
}
package com.thread.ch8;
import java.util.function.Consumer;
public class FutureService {
public <T> Future<T> submit(final FutureTask<T> task) {
AsynFuture<T> asynFuture = new AsynFuture<>();
new Thread(() -> {
T result = task.call();
asynFuture.done(result);
}).start();
return asynFuture;
}
//java8方法推导,consumer回调
public <T> Future<T> submit(final FutureTask<T> task, final Consumer<T> consumer){
AsynFuture<T> asynFuture = new AsynFuture<>();
new Thread(()->{
T result = task.call();
asynFuture.done(result);
consumer.accept(result);
}).start();
return asynFuture;
}
}
package com.thread.ch8;
public class SyncInvoker {
public static void main(String[] args) {
FutureService futureService = new FutureService();
FutureTaskImpl futureTask = new FutureTaskImpl();
/* futureService.submit(()->{
try {
Thread.sleep(10000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "FINISH";
}, System.out::println);*/
futureService.submit(futureTask, System.out::println);
System.out.println("===========");
System.out.println(" do other thing.");
}
}
以上是 多线程future设计械 的全部内容, 来源链接: utcz.com/z/513619.html