How to run threads in parallel in Android

I am trying to run multiple threads in parallel. I tried to achieve this with multiple instances of the stream. My assumption is that it will be executed at the same time; however, threads execute in sequence.

Here is the 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 loop executes one after another

Counting from 0 to 99 in a thread A, followed by the same in Thread Band Thread C.

Based on this, I came to the conclusion that they are not executed in parallel, as I thought, they will be, but rather in sequence.

How can parallel execution be done on Android?

+5
4

, , , . , 100 , , , . , "", , , - ( 10k 100k):

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

, "" . AsyncTask .

+9

AsyncTask, Thread_POOL_EXECUTOR .

+3

Excutors, .

ExecutorService pool = Executors.newFixedThreadPool(numOfYourThreads)

But be careful not to run too many threads and overload your processor.

Edit: As I can see, the canon seems to be AsyncTask, which only applies to short operations. If you need to use a longer task, use IntentService or ExecutorService.

+2
source

This is how to use ExecutorService

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

executorService.shutdown();
0
source

All Articles