我正在使用多线程和ExecutorService来检查它们何时全部完成。问题在于,当我调用方法初始化ExecutorService并执行线程(我在onCreate()中调用它)时,启动活动时会出现延迟。以下是我的代码:
public void test(){
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(new SomeTask());
executor.execute(new SomeTask());
executor.execute(new SomeTask());
executor.shutdown();
try{
boolean finshed = executor.awaitTermination(1, TimeUnit.MINUTES);
}
catch (InterruptedException e){e.printStackTrace();}
if (executor.isTerminated()){
Toast.makeText(AddVehicleActivity.this,"DONE",Toast.LENGTH_LONG).show();
}
}
private class SomeTask implements Runnable
{
@Override
public void run(){
final Request request = new Request.Builder()
.addHeader("Authorization",SharedPreferencesHelper.getToken())
.url("http://sapron.uveee.ru/api/vehicles/marks/get")
.build();
try{
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}else{
Gson gson = new GsonBuilder().create();
MarkResponse resp = gson.fromJson(response.body().charStream(), MarkResponse.class);
for (int i = 0;i<resp.getData().size();i++){
Log.i("SHOWVEH", "onResponse: " + resp.getData().get(i).getImg());
}
}
}catch (IOException e){
e.printStackTrace();}
}
}
Please help. Thanks.