Java多线程实现原理

2.Callable方式

FutureTask task1 = new FutureTask(new Callable(){

public String call(){

return “线程实现方式”;

}

});

Thread thread = new Thread(task1);

thread.start();

try {

System.out.println(task1.get());

} catch (InterruptedException e) {

e.printStackTrace();

} catch (ExecutionException e) {

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 “线程池实现方式”;

}

};

Futur

必看视频!获取2024年最新Java开发全套学习资料 备注Java

eTask task = new FutureTask<>(callable);

最后

本人也收藏了一份Java面试核心知识点来应付面试,借着这次机会可以送给我的读者朋友们:

目录:

二面蚂蚁金服(交叉面),已拿offer,Java岗定级阿里P6

Java面试核心知识点

一共有30个专题,足够读者朋友们应付面试啦,也节省朋友们去到处搜刮资料自己整理的时间!

二面蚂蚁金服(交叉面),已拿offer,Java岗定级阿里P6

Java面试核心知识点
试,借着这次机会可以送给我的读者朋友们:

目录:

[外链图片转存中…(img-cZqtJxMn-1716457907622)]

Java面试核心知识点

一共有30个专题,足够读者朋友们应付面试啦,也节省朋友们去到处搜刮资料自己整理的时间!

[外链图片转存中…(img-OuQ1eNod-1716457907622)]

Java面试核心知识点

  • 11
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值