Java – executorservice seems to run threads on the UI?
Iam tried to use executorservice to run some code to connect my client to the server Obviously Iam tried to make it run on a separate thread to the UI thread, but my UI froze during code execution This is not what I want I thought executorservice would run on a separate thread? Here is my code
@Override public void registerDevice() { ExecutorService exservice = Executors.newFixedThreadPool(10); Future<Boolean> future = exservice.submit(new Callable() { @Override public Boolean call() throws Exception { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); try { Thread.sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); } reghandler.post(new Runnable() { @Override public void run() { regpresenter.updateUIProgress(); } }); return true; } }); exservice.shutdown(); try { Boolean done = future.get(10,TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); warningstr = "Server call timed out!"; } exservice.shutDownNow(); }
I would appreciate it if someone could tell me why this does not run separately to the UI thread After reading all the documentation about the performer service, maybe something is missing I have another solution that seems to work, but it creates a loop dependency with TimerTask in the run method of another thread If the thread is active, TimerTask will interrupt the thread after timeout So I really don't want to use that solution I also just test the current overtime I missed some code in the method because it was not relevant to my problem Thanks again
Solution
The following code indicates waiting for the task result (the maximum value is 10 seconds timeout)
Boolean done = future.get(10,TimeUnit.SECONDS);
If you don't want to wait until the task is completed, don't call get()