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

来源:互联网 发布:小米3支持电信4g网络吗 编辑:程序博客网 时间:2024/05/17 02:41
实现带返回值的线程调用方式有很多, 这里主要是借助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
原创粉丝点击