• Post Reply Bookmark Topic Watch Topic
  • New Topic

asking about threads as a begginer  RSS feed

 
kumar abhay
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
here is the programme given below:

Question 1:
my question is that y child thread is running everytime 2 times than of main thread.could u please clearify it more.
i will be really thankfull to u.
kumar abhay
[ edited to add 'code' tags (for readability) - George ]
[ July 17, 2002: Message edited by: George Brown ]
 
Snigdha Solanki
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is becuase of sleep interval. In your code
the main thread is sleeping for 1000ms and child
thread is sleeping for 500ms.Increase the sleep
interval of child process to 1000ms and you will
get different output.Something like this:
Child Thread:Thread[Demo Thread,5,main]
Main Thread:5
Child thread:5
Main Thread:4
Child thread:4
Main Thread:3
Child thread:3
Main Thread:2
Child thread:2
Main Thread:1
Child thread:1
Main Thread Exiting
Exiting Child Thread
[ June 28, 2002: Message edited by: Snigdha Solanki ]
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is not necessary to both implement Runnable AND encapsulate another thread. I altered yoru program below to show how you should/could have done it.

This is typically how Runnable is used.
Also, threads will NOT run in a guaranteed order. The OS will decide when to switch off a thread and when to switch on one. Just because you put in certain timing does not mean that is what you will see on the output. Not to menation that both threads could try to access System.out at the same time and you could get some overwritten output kind of blended between the two. The OS is not a realtime OS and as such done expect fair time sharing, though the OS will attempt to be fair, its not guaranteed.
 
Kevin McLain
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually since PrintStream.println properly synchronizes access you won't get statements from different threads showing up on the console.
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Kevin McLain:
Actually since PrintStream.println properly synchronizes access you won't get statements from different threads showing up on the console.

yes your right.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!