Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Multithreading is not working  RSS feed

 
Rajesh Santhanakrishnan
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi , I was learning multithreading concepts from a tutorial. I tried the below code.




I was expecting the output as
0
0
1
1
2
2

but I am getting as

0
1
2
0
1
2

It is working sequentially and I don't find to observe any threading concept. Any idea
 
Henry Wong
author
Sheriff
Posts: 22846
119
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rajesh Santhanakrishnan wrote:
It is working sequentially and I don't find to observe any threading concept. Any idea


Trying making the loops print out more numbers (like 1000 instead of 3)... what you are seeing is a race condition, where the first thread finishes everything before the second thread is started (or close to it).

Henry
 
drac yang
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
after all, the first thread starts before the second thread, which just means there's time gap very small though, and plus the first thread working time is very short.
 
Jason Bullers
Ranch Hand
Posts: 111
8
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rajesh Santhanakrishnan wrote:
It is working sequentially and I don't find to observe any threading concept. Any idea

It's working sequentially this time, but that doesn't mean it always will. As Henry mentioned, it'll be a lot easier to see that if you increase the upper bound on the loop. Nothing in the code you showed sets up any sort of dependency or ordering between the two runners, so the output is going to be based solely on when and how often the JVM decides to switch between the threads.
 
Tim Halloran
Greenhorn
Posts: 5
Android C++ Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is code that will show more random output.




  • A count down latch is used to make both thread start their output work at roughly the "same time" (will depend somewhat on the scheduler and hardware and os)
  • I got rid of the sleep (not sure what that was for)


  • I do get interleaved output but, as expected, it varies by run :-)
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!