How to run threads in parallel in Android

Viewed 9084

I'm trying to run multiple threads in parallel. I tried to achieve this by having multiple instances of a thread. My assumption is that it will be executed simultaneously; however, the threads are being executed in a sequence.

Here's a simple code I tested:

new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i=0; i<100; i++) {
                LMLog.info("THREAD", "Counting " + i + " in Thread A");
            }
        }
    }).start();
    new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i=0; i<100; i++) {
                LMLog.info("THREAD", "Counting " + i + " in Thread B");
            }
        }
    }).start();
    new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i=0; i<100; i++) {
                LMLog.info("THREAD", "Counting " + i + " in Thread C");
            }
        }
    }).start();

And the log shows that the for loops are being executed one after another

Counting from 0 to 99 in Thread A, followed by the same thing in Thread B and Thread C.

Based on this, I concluded that they were not being executed in parallel as I thought they would be, but rather in a sequence.

How can I achieve parallel execution in Android then?

4 Answers

This is how to use ExecutorService

ExecutorService executorService = Executors.newFixedThreadPool(10);
  executorService.execute(new Runnable() {
        public void run() {
            // do something
        }
    });

executorService.shutdown();
Related