IntelliJ Java IDE
The moose likes Threads and Synchronization and the fly likes asking about threads as a begginer Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "asking about threads as a begginer" Watch "asking about threads as a begginer" New topic
Author

asking about threads as a begginer

kumar abhay
Ranch Hand

Joined: Oct 02, 2001
Posts: 53
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

Joined: Sep 07, 2000
Posts: 128
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 ]

Snigdha<br />Sun Certified Programmer for the Java™ 2 Platform
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1158

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

Joined: Jul 04, 2002
Posts: 4
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

Joined: Oct 05, 2001
Posts: 1158

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.
 
IntelliJ Java IDE
 
subject: asking about threads as a begginer
 
Threads others viewed
Threads
What are those two threads???
Confusion in Thread
threads in java
Threads
WebSphere development made easy
without the weight of IBM tools
http://www.myeclipseide.com