I am working on Java implementation of an Android class AsyncTask I am using the Future and Callable classes of Java . Here is my Async Task :-
public abstract class AsyncTask<Params,Result>{
ExecutorService executor = Executors.newFixedThreadPool(10);
protected abstract Result runInBackground(Params params);
protected abstract void postExecute(Result result);
private Future<Result> future;
public void execute(Params params) {
future = executor.submit(new AsyncCallable<Params, Result>(params, this));
try {
postExecute(future.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
My AsyncCallable class which implements the Java Callable interface :-
public class AsyncCallable<Params,Result> implements Callable<Result>{
private Params params;
private AsyncTask<Params, Result> asyncTask;
public AsyncCallable(Params params,AsyncTask<Params, Result> asyncTask) {
this.params = params;
this.asyncTask = asyncTask;
}
@Override
public Result call() throws Exception {
System.out.println(Thread.currentThread().getName()+" is executing");
return asyncTask.runInBackground(params);
}
}
And Here is my driver program which i am using to test the above program .
public static void main(String args[]){
new AsyncTask<String, String>() {
@Override
protected String runInBackground(String params) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "Hello "+params;
}
@Override
protected void postExecute(String result) {
System.out.println(result+" AFter 10 sec");
}
}.execute("World");
new AsyncTask<String, String>() {
@Override
protected String runInBackground(String params) {
try {
//Thread.sleep(2000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "Hello "+params;
}
@Override
protected void postExecute(String result) {
System.out.println(result+" AFter 2 sec");
}
}.execute("World");
}
And here is the output which i am getting :-
pool-1-thread-1 is executing
Hello World AFter 10 sec
pool-2-thread-1 is executing
Hello World AFter 2 sec
If you see , my code is not running asynchronously , i.e both my AsyncTask are being implemented on the same thread . That is why it is waiting for the first Task to complete and after that my second AsyncTask is getting called . Can you help me figure out the problem in my code