aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes For loop using thread as object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "For loop using thread as object" Watch "For loop using thread as object" New topic
Author

For loop using thread as object

Saurabh Vohra
Greenhorn

Joined: Mar 19, 2014
Posts: 4




This question is from Exam Lab 6

i have a problem in understanding this loop


why it says that you are starting same thread twice. So it will throw an exception

I know that you cant start thread twice and you wil get exception if you try to attempt.

But for loop is executing twice , wont it gets executed on two different objects?
I mean wont be its like that

new TRead().getInst().start(); // Ist thread
new TRead().getInst().start(); // 2nd thread



Thanks for reply in advance
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1824
    
    7

No there is but one instance statically declared and initialized at line 2.
The method getInst() simply returns that instance every time it's called.
If tr hadn't be declared static you'd be correct in your assumption.


Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Rico Felix
Ranch Hand

Joined: Mar 08, 2014
Posts: 304
    
    4

Jelle Klap wrote:No there is but one instance statically declared and initialized at line 2.
The method getInst() simply returns that instance every time it's called.
If tr hadn't be declared static you'd be correct in your assumption.


That is exactly what is happening... The for loop was only included in the code to stray you away from what you should already know.

The instance method getInst() is returning the static variable tr.

In the for loop it first returns the reference to tr and invokes to start method on the Thread object. The Thread object now transitions from the new state to runnable state and later to running state by the scheduler.

The loop is entered a second time and returns the same refrence tr and tries to invoke the start method again.

Since a Thread object can only be started once, it throws an IllegalThreadStateException
leometal Chen
Greenhorn

Joined: Dec 02, 2013
Posts: 8
singleton pattern and invoke start() twice
Paweł Baczyński
Bartender

Joined: Apr 18, 2013
Posts: 1021
    
  16

leometal Chen wrote:singleton pattern and invoke start() twice

I don't see any singleton here.


Formely Pawel Pawlowicz
 
 
subject: For loop using thread as object