Search code examples
androidrunnable

Android studio runnable, threads


I have two options to execute my program (I need to have Out_str as a result).

Option 1:

            Out_str = "";
            for (i = 1; i <= 20000; i++) {
                Out_str = Out_str + "word";
            }

Option2:

            Runnable runnable1 = new Runnable() {
                public void run() {

                    Out_str1 = "";
                    for (i1 = 1; i1 <= 10000; i1++) {
                        Out_str1 = Out_str1 + "word";
                    }
                }
            };

            Runnable runnable2 = new Runnable() {
                public void run() {
                    Out_str2 = "";
                    for (i2 = 1; i2 <= 10000; i2++) {
                        Out_str2 = Out_str2 + "word";

                    }
                }
            };


            Thread thread1 = new Thread(runnable1);
            thread1.start();

            Thread thread2 = new Thread(runnable2);
            thread2.start();

Why using threads does not make my program execute faster (in both cases the execution takes approx 12 sec with my laptop)? What shall I use in this case (to make it faster to obtain Out_str)? Will using services make help in this case?


Solution

  • The Thread allows you to run processes concurrently. You haven't gained any processing power though, with equal priority your threads would be run in a round-robin way I would guess.