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?
On a system with more than one processor or CPU cores (as is common with modern processors), multiple processes or threads can be executed in parallel.
Within a process or program, we can run multiple threads concurrently to improve the performance. Threads, unlike heavyweight process, are lightweight and run inside a single process – they share the same address space, the resources allocated and the environment of that process.
Developers multithread Android applications in order to improve their performance and usability. By spinning off processor- or resource-intensive tasks into their own threads, the rest of the program can continue to operate while these processor intensive tasks finish working.
Seven Threading Patterns in Android.
I might be wrong, but I think your conclusion is faulty. The reason for it is that counting to 100 takes such a short time that it probably takes more time to instantiate a new Thread and start it. If you want to ensure that your test is "valid" you should first instantiate all 3 threads and then start them all, something like this (also increase counter to 10k or 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();
This is purely for making your 'test' work. You can also use AsyncTask or some other methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With