aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Threads Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Threads" Watch "Threads" New topic
Author

Threads

Muhammad Farooq
Ranch Hand

Joined: May 08, 2001
Posts: 356
Why in the following code, the thread start after executing the println command.
=========================================================
class MyThread implements Runnable
{

public void run()
{
System.out.println("In run()");
}
public static void main(String[] args)
{
MyThread a =new MyThread();
MyThread b =new MyThread();
new Thread(a).start();
new Thread(b).start();

System.out.println("End of main()");
}
}
===========================================================
--Farooq

Muhammad Farooq<br />Sun Certified Programmer for Java 2 Platform<br />Oracle8i Certified Professional Database Administrator
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Helo!
Scheduler moves in mysterious ways and gives the thread of the MyThread more Running state than the "spawned" threads.
There are, however, some means to control this. You might want to place Thread.yield() right after the start method of the other threads. Keyword synchronized might help to keep the code running in the run() method.
Thats it in the nutshell. For detailed explanation see some good text book or wait for some Java guru to notify this topic.
------------------
Antti Barck
It Solutions Consultant, NSD Oy
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
Muhammad
I assume you mean why does it look like the two threads are not starting until after the 'End of main' message appears. The Threads do not actually start when you call the start method. start does some behind the scenes work to make the Thread able to run in its own process and registers the Thread with the scheduler. It is the scheduler that decides when a thread is allocated cpu time. In this case the scheduler lets the main method finish running before it gives the cpu to either of the other two. If you put some other code into the main (like a loop or something else that takes a few seconds) you may see the other two threads print their messages before main does.
You could also try to increase the priority of the two threads and see if the scheduler behaved differently.
No one specific outcome is guaranteed in a situation like this. Some of it is system dependent and some is dependent on the implementation of the JVM.

hope this helped you out

Dave
[This message has been edited by Dave Vick (edited July 25, 2001).]


Dave
 
I agree. Here's the link: jrebel
 
subject: Threads
 
Similar Threads
notifyAll()
Thread Question---start()
Thread Question
Calling Thread By Start() and Run()
Thread Doubt