如果要用能返回值得线程,得用到Callable 和FutureTask,但是返回值是阻塞式的,因此自己实现了个异步返回值的线程。
功能简单了点,只是个思路。
package thread;
import java.text.SimpleDateFormat;
import thread.FutureJob.CallBack;
interface ReturnBackRunnable<T>{
T run();
}
class FutureJob<T> implements Runnable{
interface CallBack<T>{
void callBack(T t);
}
private CallBack<T> mCallBack;
private ReturnBackRunnable<T> returnBackRunnable;
public FutureJob(ReturnBackRunnable<T> returnBackRunnable) {
this.returnBackRunnable = returnBackRunnable;
}
public FutureJob(CallBack<T> mCallBack, ReturnBackRunnable<T> returnBackRunnable) {
this.mCallBack = mCallBack;
this.returnBackRunnable = returnBackRunnable;
}
public void setCallBack(CallBack<T> mCallBack) {
this.mCallBack = mCallBack;
}
@Override
public void run() {
if(returnBackRunnable!=null){
T value= returnBackRunnable.run();
if(mCallBack!=null){
mCallBack.callBack(value);
}
}
}
}
public class TCallable {
public static void main(String[] args) {
FutureJob<String> futureJob = new FutureJob<String>(new ReturnBackRunnable<String>() {
@Override
public String run() {
try {
Thread.sleep(1000*10);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "OK";
}
});
futureJob.setCallBack(new CallBack<String>() {
@Override
public void callBack(String t) {
System.out.println("the back value is "+t);
}
});
System.out.println(formatDate(System.currentTimeMillis()));
new Thread(futureJob).start();
System.out.println(formatDate(System.currentTimeMillis()));
}
private static String formatDate(long date){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return simpleDateFormat.format(date);
}
}
执行结果:
2017/06/22 23:01:53
2017/06/22 23:01:53
the back value is OK
从结果看,执行完start后,返回main继续执行,结果是异步返回的。