user11452194
user11452194

Reputation: 53

How to interpret and explain the execution result of this java threading program

I am new to threads. I read an article from https://www.math.uni-hamburg.de/doc/java/tutorial/essential/threads/definition.html

"A thread is a single sequential flow of control within a program." It is still intangible to me, it would be very helpful if someone can give another example and explain more.

Then I check out some examples with the following code.

class SimpleThread extends Thread {
     public SimpleThread(String str) {
         super(str);
     }
     public void run() {
         for (int i = 0; i < 10; i++) {
             System.out.println(i + " " + getName());
             try {

                 # sleep((int)(Math.random() * 1000));
                 /* I have changed Math.random() to 0.5 so that all will sleep with same amount of time */
                 sleep((int)(0.5 * 1000));
             } catch (InterruptedException e) {}
         }
         System.out.println("DONE! " + getName());
     }
 }

 class ThreeThreadsTest {
     public static void main (String[] args) {
         new SimpleThread("Jamaica").start();
         new SimpleThread("Fiji").start();
         new SimpleThread("Bora Bora").start();
     }
 }

In the main function of ThreeThreadsTest, the three threads are created one by one, the result should follow a pattern like this:

0 Jamaica
0 Fiji
0 Bora Bora
1 Jamaica
1 Fiji
1 Bora Bora
2 Jamaica
2 Fiji
2 Bora Bora ...

but instead the result is like this:
0 Jamaica
0 Bora Bora
0 Fiji
1 Jamaica
1 Bora Bora
1 Fiji
2 Jamaica
2 Fiji
2 Bora Bora
3 Jamaica
3 Fiji
3 Bora Bora
4 Bora Bora
4 Jamaica
4 Fiji
5 Bora Bora
5 Jamaica
5 Fiji
6 Bora Bora
6 Jamaica
6 Fiji
7 Bora Bora
7 Fiji
7 Jamaica
8 Bora Bora
8 Jamaica
8 Fiji
9 Bora Bora
9 Fiji
9 Jamaica
DONE! Fiji
DONE! Bora Bora
DONE! Jamaica

Can someone explain why this will happen?

Upvotes: 1

Views: 58

Answers (2)

SirFartALot
SirFartALot

Reputation: 1225

Threads inside have a "sequential flow", but not so for multiple Threads.

"the same amount of time" is not as fixed as it seems. Within a CPU a time of a millisecond are like aeons. The CPU will wait for your defined milliseconds but after the "wait" it's up to the cpu, which thread it will resume first.

Upvotes: 1

Michel_T.
Michel_T.

Reputation: 2821

Thread.start() puts a thread into a queue of threads which are ready to be executed. Then OS picks any of ready threads and executes it. There's no warranty which thread will be picked the next, so the order of execution is rather random.

Upvotes: 3

Related Questions