e.printStackTrace();
}
a.使用线程实现方式
主要是将Callable的实例对象通过FutureTask包装了一下,可以看下FutureTask中构造方法的源码
FutureTask 实现RunnableFuture接口,而RunnableFuture接口继承Runnable, Future接口
因此FutureTask可以包装的Callable的实例中的call()在run()中执行,所以这种方式就等于将Runnable实现的子类实例放入到Thread的构造方法中,子类的run()方法正好是重写里面调用call();
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
另外,FutureTask的构造方法传入的参数除了Callable之外也支持Runnable,它的操作主要是将Runnable实现的子类通过RunnableAdapter转化为Callable,源码如下
public FutureTask(Runnable runnable, V result) {
this.callable = Executors.callable(runnable, result);
this.state = NEW; // ensure visibility of callable
}
public static Callable callable(Runnable task, T result) {
if (task == null)
throw new NullPointerException();
return new RunnableAdapter(task, result);
}
b.使用线程池方式实现
ThreadPoolExecutor threadPool = (ThreadPoolExecutor)Executors.newFixedThreadPool (10);
Callable callable = new Callable() {
@Override
public Object call() throws Exception {
return “线程池实现方式”;
}
};
FutureTask task = new FutureTask<>(callable);
threadPool.submit(task);
try {
System.out.println(task.get());;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
submit()传入的是Runnable, FutureTask继承的就是Runnable,sub
必看视频!获取2024年最新Java开发全套学习资料 备注Java
mit里面的execute的运行是根据newFixedThreadPool中的execute()运行。下面为submit()的源码
public Future<?> submit(Runnable task) {
if (task == null) throw new NullPointerException();
RunnableFuture ftask = newTaskFor(task, null);
execute(ftask);
return ftask;
}
总结
如果你选择了IT行业并坚定的走下去,这个方向肯定是没有一丝问题的,这是个高薪行业,但是高薪是凭自己的努力学习获取来的,这次我把P8大佬用过的一些学习笔记(pdf)都整理在本文中了
《Java中高级核心知识全面解析》
小米商场项目实战,别再担心面试没有实战项目:
薪行业,但是高薪是凭自己的努力学习获取来的,这次我把P8大佬用过的一些学习笔记(pdf)都整理在本文中了
《Java中高级核心知识全面解析》
[外链图片转存中…(img-UgJlEqFK-1716457872074)]
小米商场项目实战,别再担心面试没有实战项目:
[外链图片转存中…(img-L0PUWKCl-1716457872075)]