理解高并发(16).自己动手编写Future、Callable

实现带返回值的线程调用方式有很多, 这里主要是借助LockSupport工具来实现。

MyFuture.java类
功能职责:
1、实现runnable接口,使其具体线程的特质
2、 提供future的get方法,使调用者能够获取到返回值
package com.test.thread.demo13;

import java.util.concurrent.locks.LockSupport;

public class MyFuture<T> implements Runnable{
MyTask task;
Result<T> result;
Thread current;
public MyFuture(MyTask task){
this.task = task;
result = new Result<T>();
current = Thread.currentThread();
System.out.println("process thread is:" + Thread.currentThread().getName() + ", call thread is:" + current.getName());
}
@SuppressWarnings("unchecked")
public void run(){
Object value = task.call();
result.setDone(true);
result.setResult((T)value);
LockSupport.unpark(current);
System.out.println("process thread is:" + Thread.currentThread().getName() + ", call thread is:" + current.getName());
}
public T get(){
for(;;){
if(!result.isDone){
LockSupport.park(current);
}else{
break;
}
}
System.out.println("process thread is:" + Thread.currentThread().getName() + ", call thread is:" + current.getName());
return result.getResult();
}
@SuppressWarnings("hiding")
class Result<T>{
boolean isDone = false;
T result;
public void setDone(boolean status){
this.isDone = status;
}
public boolean getStatus(){
return this.isDone;
}
public void setResult(T result){
this.result = result;
}
public T getResult(){
return result;
}
}
}

MyTask.java类:
功能职责: 具体业务实现
package com.test.thread.demo13;

public class MyTask {
public String call(){
try {
Thread.sleep(5000L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "hello";
}
}


MyTaskTest.java类:
测试类
package com.test.thread.demo13;

public class MyTaskTest {
public static void main(String[] args) {
MyFuture<String> future = new MyFuture<String>(new MyTask());
Thread thread = new Thread(future);
thread.start();
System.out.println("============over 1");
String result = future.get();
System.out.println("result:" + result);
System.out.println("============over 2");
}
}


运行效果:
process thread is:main, call thread is:main
============over 1
process thread is:Thread-0, call thread is:main
process thread is:main, call thread is:main
result:hello //以下2行必定会在子线程运行完后才输出
============over 2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值