package com.example.task;
import java.util.concurrent.Callable;
/**
* 开启线程,任务执行、返回数据代理对象
*/
public class AsyncTask {
public <T> CallableData<T> execute(final Callable<T> callable) {
final CallableData<T> data = new CallableData<>();
new Thread(new Runnable() {
@Override
public void run() {
data.setCallable(callable);
}
}).start();
return data;
}
}
package com.example.task;
import java.util.concurrent.Callable;
public class CallableData<T> {
// private CountDownLatch countDownLatch = new CountDownLatch(1);
private T result;
private boolean isDone = false;
public synchronized void setCallable(Callable<T> callable) {
if ( isDone ) return ;
try {
this.result = callable.call();
} catch (Exception e) {
e.printStackTrace();
}
// countDownLatch.countDown();
isDone = true;
notify();
}
public synchronized T get() {
if (!isDone) {
try {
wait();
// countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return this.result;
}
}
package com.example.task;
import java.util.concurrent.Callable;
public class Main {
public static void main(String[] args) {
AsyncTask task = new AsyncTask();
CallableData<String> data1 = task.execute(new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("====执行任务1====");
Thread.sleep(2000);
System.out.println("====完成1====");
return "执行完毕结果1";
}
});
CallableData<String> data2 = task.execute(new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("====执行任务2====");
Thread.sleep(5000);
System.out.println("====完成2====");
return "执行完毕结果2";
}
});
System.out.println(data1.get());
System.out.println(data2.get());
}
}