File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes start() of Thread class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "start() of Thread class" Watch "start() of Thread class" New topic
Author

start() of Thread class

rajashree ghatak
Ranch Hand

Joined: Mar 10, 2001
Posts: 151
hi everyOne,
pls look at the below code and comment on it:
public void run()
{
for (int i=0;i<6;i++)<br /> System.out.println("Hello"+i);<br /> }<br /> public static void main(String[] r)<br /> {<br /> Thread t=new Thread(new ttest09());//ttest09 is a Runnable object<br /> t.start();<br /> for(int i=15;i>0;i--)
System.out.println("World"+i);
t.start();
System.out.println("main() Ending");
}
Output is
15 times "World" and 6 times "Hello" is appearing and at the end "main() Ending" appears.
My query is why isn't "Hello" again getting printed 6 times since start() is called twice on Thread t?
My 2nd query:if i=10 in 2nd for loop,output varies ne being 10 times "World" and 6 times "Hello" appearing alternatively and no Exception being thrown.
the second output being "World" and "Hello" being printed at a random order and IllegalThreadStateException being thrown.

i know why the above exception gets generated.what i want to know is if asked in the EXAM what should be our answer to the 2nd query and are such kind of Qs whose output is not guaranteed being asked?
rajashree.

Roopa Bagur
Ranch Hand

Joined: Nov 03, 2000
Posts: 267
1.From what I understand you cannot call the start method twice on the same thread but if you want to re run the same thread just directly call the run() method of the thread.
2. I have seen this type of question in some mock exams so I assume it might appear in the real exam to.
Any body correct me if I am wrong
Originally posted by rajashree ghatak:
hi everyOne,
pls look at the below code and comment on it:
public void run()
{
for (int i=0;i<6;i++)<br /> System.out.println("Hello"+i);<br /> }<br /> public static void main(String[] r)<br /> {<br /> Thread t=new Thread(new ttest09());//ttest09 is a Runnable object<br /> t.start();<br /> for(int i=15;i>0;i--)
System.out.println("World"+i);
t.start();
System.out.println("main() Ending");
}
Output is
15 times "World" and 6 times "Hello" is appearing and at the end "main() Ending" appears.
[b] My query is why isn't "Hello" again getting printed 6 times since start() is called twice on Thread t?
My 2nd query:if i=10 in 2nd for loop,output varies ne being 10 times "World" and 6 times "Hello" appearing alternatively and no Exception being thrown.
the second output being "World" and "Hello" being printed at a random order and IllegalThreadStateException being thrown.

i know why the above exception gets generated.what i want to know is if asked in the EXAM what should be our answer to the 2nd query and are such kind of Qs whose output is not guaranteed being asked?
rajashree.
[/B]

leena rane
Ranch Hand

Joined: Aug 13, 2001
Posts: 280
http://www.javaranch.com/ubb/Forum24/HTML/011959.html
see if this answers ur question
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
rajashree
The other problem you may be having is that if you create a Thread object with a runnable target in its constructor, it is the runnable objects run method that gets called.
So if the code you posted is in a different class that would explain no output.
Also, as Roopa, expalined you cant call start on the same thread object twice.

------------------
Dave
Sun Certified Programmer for the Java� 2 Platform


Dave
rajashree ghatak
Ranch Hand

Joined: Mar 10, 2001
Posts: 151
hi all
thanx for ur responses to my query.i have replaced the 2nd start()method in my code with run()method.
But the output is still varies with sometimes
1) 15 times "World" and 12 times "Hello"
2) 15 times "World" and only 6 times "Hello"
kindly tell me why is "Hello" not getting printed 12 times always, now that run() method is called directly.
rajashree.
rajashree ghatak
Ranch Hand

Joined: Mar 10, 2001
Posts: 151
hi all
thanx for ur responses to my query.i have replaced the 2nd start()method in my code with run()method.
But the output is still varies with sometimes
1) 15 times "World" and 12 times "Hello"
2) 15 times "World" and only 6 times "Hello"
kindly tell me why is "Hello" not getting printed 12 times always, now that run() method is called directly.
rajashree.
Ragu Sivaraman
Ranch Hand

Joined: Jul 20, 2001
Posts: 464
Originally posted by rajashree ghatak:
hi all
thanx for ur responses to my query.i have replaced the 2nd start()method in my code with run()method.
But the output is still varies with sometimes
1) 15 times "World" and 12 times "Hello"
2) 15 times "World" and only 6 times "Hello"
kindly tell me why is "Hello" not getting printed 12 times always, now that run() method is called directly.
rajashree.

Rajashree.
I did remove second t.start() and gave the run() method as instance method and I didnt have any problem
15times World and 12 times of Hello is consistent
(OS: Win98/JDK 1.3)

But I have a pecuilar issue.
I wanted to discuss with all of the thread gurus
Please take a look at this code

public void run(){
for (int i=0;i<6;i++)<br /> System.out.println("Hello"+i);<br /> }<br /> public static void main(String[] r){<br /> Thread t=new Thread(new ttest09());//ttest09 is a Runnable object<br /> for(int i=15;i>0;i--)
System.out.println("World"+i);
t.start();
System.out.println("main() Ending");
}
}
All along my understanding of parent(main)/thread and user thread combo was ... Parent executes first and then child gets to run... and the runtime or the application will be alive until
and otherwise the child ends...
But the pecularity of threading behaviour confuses me little bit

If you compile the code above and run it, it just works as per my understanding... ie
main()-first //15 times of World followed by "main() Ending"
userthread-second //5 times of Hello from run()
But, if i move t.start() line up ie before the for loop
then the hell breaks loose....
The output is very erratic and inconsistent
and its longer main() first / user thread second
Is this behaviour OS dependent (thread scheduling algorithm like
pre-emptive / round robin etc...)
Or there is no norm that main() should be executed first and the user thread gets to execute second?

Can someone clarify this for me please?

rajashree ghatak
Ranch Hand

Joined: Mar 10, 2001
Posts: 151
hi Ragu,
i am compiling and running my code in jdk1.2.1 on Win98 platform.i once again tried but still the output varies and 12 times "Hello" doesn't appear consistently with most of the time being only 6 times "Hello" getting printed.
why is such a difference?is it something to do with versions 1.2.1/1.3?
as far as ur query is concerned with start() being called just before the for loop i am eratic results on execution.
rajashree.

Gagan Indus
Ranch Hand

Joined: Feb 28, 2001
Posts: 346
hi ! lotz of things in this happening-post require discussion
first , in The original code by Rajashree ( in which we have two calls to method start() ) , i was expecting IllegalThreadStateException to be thrown at runtime , as per API docs

....start() method throws IllegalThreadStateException if the thread was already started.....

But no such execption is ever thrown ?
I rewritten the code in many fashions , experimented wid it , and as it turn outs It is a bug of java runtime , check it at : http://developer.java.sun.com/developer/bugParade/bugs/4422466.html
One more relevant bug is : http://developer.java.sun.com/developer/bugParade/bugs/4180576.html
Hopefully , this get fixed in some next release !
Now , as for Ragu's query , yes Ragu , u already guessed it , this behaviour is JVM-implementation dependent .
When two or more Threads become ready to run,( + those who r already running ),then which of all these Threads will get to run for how long , n when will they get to run is JVM-implementation dependent ( preemptive , time-slice ) ( Threads priorities can also effect this behaviour a little , but in our case all user threads have same priority )
scheduling implementation vary from platform to platform, preemptive scheduler may preempt (pauses) a running thread to allow other threads to execute ,a non-preemtive scheduler doesn't pause a thread.
Now Turning specific to your case , I guess u r using Windows-based JVM , which is time-sliced. For these type of schedulers , i quote a very informative line from khalid page 285 ...

.. running thread is allowed to execute for a fixed length of time , after which it moves to ready-to-run state to await its turn to run again....

That is what is exactly happening with your main() thread. After main's time-slice expires , it moves to ready to run , n Thread t gets it slice , after t's slice expires ,main gets it again , then t , n so on... until they finish.This explains outputs appearing alternatively .
I hope , u shld be clear now. ( and remember,there is NOsuch norm that main() should be executed first and the user thread gets to execute second. Infact , main may not even get to run again , until some high priority user-thread finish!! .Its all implementation dependent )

And now , about problem in changed code by Rajashree . Yes , Rajashree , there is definetly some problem with this code. I tested it on various versions .
Consider for eg :

The output of above code as it is :
World15 World14 World13 World12 World11 World10 World9 Hello0 World8 Hello1 Worl
d7 Hello2 World6 Hello3 World5 Hello4 World4 Hello5 World3 World2 World1 main()
Ending

tht is , 15 times "World" , n 6 times "Hello"
Now Try changing the LINE#1 in above code to "test.run();" , and the output changes to :
World15 World14 World13 World12 World11 World10 World9 World8 World7 World6 Worl
d5 World4 World3 World2 Hello0 World1 Hello1 Hello0 Hello2 Hello1 Hello3 Hello2
Hello4 Hello3 Hello5 Hello4 Hello5 main() Ending

This is 15 times "World" n 12 times "Hello"
( PS : For given code , i always got same output on 1.2.1 n 1.3 always . The output changes only after chaging the code , but as per ur statement i can smell tht u mean to say " u getting diff output for same code at diff times"..is it? That never happened with me , even in many-many runs )
So wht exactly is wrong here? t.run() is supposed to call test.run() implicitly , as test was passed as a Runnable to <t>'s constructor?
( as sugested by run()'s implementation in Thread class :

public void run() {
if (target != null) {
target.run();
}
}
)
I experimented with the code a lot , placing lots of join() , isAlive() , run()s etc , and moving them up n down the code , and a strange observation is " Once the thread t actually gets running , the direct call to t's run() ( like t.run() ) is simply being ignored ! "
Is any such norm tht we can not call run() explicitly , while the thread in q is actually running . As far as i knw , NO such norm , becoz other code relating to this give expected outputs
(or are we dealing wid one more probable bug of JVM )
DO anyone hav any idea , thought , suggestion about this?
plz help , do comeup with anything u hav in ur mind , on this topic ...

------------------
Gagan (/^_^\)
[This message has been edited by Gagan Indus (edited September 09, 2001).]


Gagan (/^_^\) SCJP2 SCWCD IBM486 <br />Die-hard JavaMonk -- little Java a day, keeps you going.<br /><a href="http://www.objectfirst.com/blog" target="_blank" rel="nofollow">My Blog</a>
Gagan Indus
Ranch Hand

Joined: Feb 28, 2001
Posts: 346
i posted the above problem in Javaranch's Thread Forum and got a informative reply from Peter den Haan ,
u can check it at : http://www.javaranch.com/ubb/Forum27/HTML/000441.html
It solves the prob
------------------
Gagan (/^_^\)
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: start() of Thread class
 
Similar Threads
Execution flow in threads
threads
Calling Thread.run after Thread.start !
Is System.out.println(String) Thread safe?