多线程学习(五):Callable与FutureTask的简单实现
1. LazykingCallable
public interface LazykingCallable<V> {
V call();
}
2. LazykingFutureTask
public class LazykingFutureTask<V> implements Runnable{
private final LazykingCallable<V> callable;
private boolean flag = false; // 标识子线程是否执行结束
private V result;
public LazykingFutureTask(LazykingCallable<V> callable) {
this.callable = callable;
}
@Override
public void run() {
result = callable.call();
flag = true;
synchronized (this) {
this.notify();
}
}
public V get() {
if (!flag) {
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
return result;
}
}
3. CallableImpl
对编写的Callable和FutureTask进行测试
public class CallableImpl implements LazykingCallable<Integer>{
@Override
public Integer call() {
System.out.println(Thread.currentThread().getName() + ">>自定义Callable接口正在运行<<");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return 0;
}
public static void main(String[] args) {
CallableImpl callable = new CallableImpl();
LazykingFutureTask<Integer> lazykingFutureTask = new LazykingFutureTask<>(callable);
new Thread(lazykingFutureTask).start();
Integer result = lazykingFutureTask.get();
System.out.println(Thread.currentThread().getName() + ">>获取到结果:" + result + "<<");
}
}
本文是原创文章,转载请注明来自 Lazyking.site
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果
Steam卡片