如何使用Java Callable和Future设计AsyncTask?

时间:2018-04-15 09:55:37

标签: java android android-asynctask java.util.concurrent callable

我正在研究Android类的Java实现 AsyncTask 我正在使用Java的Future和Callable类。这是我的异步任务: -

if((shm=shmat(shmid,NULL,0))==(char*)-1);

实现Java Callable接口的我的AsyncCallable类: -

<?php 
//while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array 
while($res = mysqli_fetch_array($result)) { 
    echo "<tr>";
    echo "<td>".$res['topic']."</td>";
    echo "<td>".$res['issue']."</td>";
    echo "<td>".$res['solution']."</td>";
    echo "<td><div align='center'><a href=\"edit.php?id=$res[id]\">Edit</a> | <a href=\"delete.php?id=$res[id]\" onClick=\"return confirm('Are you sure you want to delete?')\">Delete</a></td>";       
}
?>

这是我用来测试上述程序的驱动程序。

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();
        }
    }

}

这是我得到的输出: -

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);
    }

}

如果你看到,我的代码没有异步运行,即我的AsyncTask都在同一个线程上实现。这就是为什么它正在等待第一个任务完成,之后我的第二个AsyncTask被调用。 你能帮我解决一下代码中的问题吗

0 个答案:

没有答案