各种线程

时间:2014-12-25 21:35:47

标签: java android multithreading

我正在尝试创建一个返回值的线程,进程正常运行但我的屏幕仍然处于锁定状态。我想要一个返回值但我的主线程继续运行的线程。

我做到了:

    public void showPartidas(int maximumDistance){
    ExecutorService es = Executors.newFixedThreadPool(1);
    Future<ArrayList<Partida>> partidas=  es.submit(new FilterPartidas(maximumDistance));
    try {
        loadInListView(partidas.get());
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

    es.shutdown();
}




class FilterPartidas implements Callable<ArrayList<Partida> > {

    private final int distance;
    private ArrayList<Partida> partidas;

    FilterPartidas(int distance) {
        this.distance = distance;
    }

    @Override
    public ArrayList<Partida> call() throws Exception {
        partidas=null;
        Download load = new Download();
        Date fecha = new Date();
        DateFormat fechaFormat = new SimpleDateFormat("yyyy-MM-dd");
        String query =  "select * from partidas where fecha >='"+fechaFormat.format(fecha)+"'";
        partidas=load.obtainPartidas(query, distance, myPosition);
        return partidas;
    }
}

1 个答案:

答案 0 :(得分:1)

partidas.get()动作是主线程在执行器中等待Callable方法完成的原因。如果您希望主线程在Callable操作执行期间仍在运行,则必须将partidas.get()操作放入专用的单独线程中,例如:

替换

Future<ArrayList<Partida>> partidas=  es.submit(new FilterPartidas(maximumDistance));
    try {
        loadInListView(partidas.get());
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

进入

final Future<ArrayList<Partida>> partidas=  es.submit(new FilterPartidas(maximumDistance));
                new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        loadInListView(partidas.get());
                    } catch (InterruptedEArrayList<Partida>xception e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

或与线程类似的操作(可能使用executor,Runnable等)。

或者您可以更改逻辑(如果可能)并将调用方法从Callable隐藏到Runnable类中。 E,G:

ExecutorService es = Executors.newFixedThreadPool(1);
es.submit(new Runnable() {
    @Override
    public void run() {
        ArrayList<Partida> partidas = logic from you Callable call;
        loadInListView(partidas);
    }
});
相关问题