Results 1 to 4 of 4
- 02-04-2012, 08:27 PM #1
Member
- Join Date
- Nov 2011
- Posts
- 27
- Rep Power
- 0
Explain the result of concurrent threads
I have this piece of code and I print answer to see. But I don't know why the answer like that:
Java Code:public class ThreadExample implements Runnable{ public Thread thread; static int i = 0; ThreadExample(){ thread = new Thread(this); thread.start(); } public static void main(String[] args) { ThreadExample example = new ThreadExample(); for(int n =0; n<1000; n++){ System.out.println("main thread "+i); i++; } } public void run(){ for(int index=0; index<1000; index++){ System.out.println("Sub thread "+i); i++; } } }
Java Code:main thread 0 Sub thread 0 Sub thread 2 Sub thread 3 Sub thread 4 Sub thread 5 Sub thread 6 Sub thread 7 Sub thread 8 Sub thread 9 Sub thread 10 Sub thread 11 Sub thread 12 main thread 1 ...
I don't know exactly what thread does together. Please explain for me this point.
thanks for all :)Last edited by hqt; 02-04-2012 at 08:32 PM.
- 02-08-2012, 12:24 PM #2
Moderator
- Join Date
- Apr 2009
- Posts
- 13,541
- Rep Power
- 27
Re: Explain the result of concurrent threads
What did you expect to see?
- 02-08-2012, 02:16 PM #3
Member
- Join Date
- Nov 2011
- Posts
- 27
- Rep Power
- 0
Re: Explain the result of concurrent threads
I think at line 14 of result, I think this line should be: main thread:12. because i has been changed to 12 at sub-Thread.
- 02-08-2012, 02:53 PM #4
Moderator
- Join Date
- Apr 2009
- Posts
- 13,541
- Rep Power
- 27
Re: Explain the result of concurrent threads
You're thinking of the lines of code as atomic.
They aren't.
The call to println() in the main thread was clearly interrupted at some point inside the method, so that the other thread could run (12 times).
Then the actual print() took place, with the text "main thread 1" already in place.
Similar Threads
-
Struts 2 error : No result defined for action / result
By sameerk in forum Web FrameworksReplies: 1Last Post: 05-17-2011, 11:15 AM -
Can someone please explain to me the proper way to display the result of a SQL query
By Turk80 in forum New To JavaReplies: 1Last Post: 04-11-2011, 02:39 AM -
tutorials/ebooks that explain Threads
By andyman99008 in forum Advanced JavaReplies: 0Last Post: 12-20-2010, 08:59 PM -
Please Explain me how i got this output.. I am new to java .. so please Explain me...
By vicky82 in forum New To JavaReplies: 3Last Post: 12-13-2010, 08:22 AM -
FileLock and file access from concurrent threads..
By fxRichard in forum Advanced JavaReplies: 5Last Post: 01-02-2009, 09:08 PM
Bookmarks