• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

For loop using thread as object

 
Saurabh Vohra
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator




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
Posts: 1952
7
Eclipse IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rico Felix
Ranch Hand
Posts: 411
5
IntelliJ IDE Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
singleton pattern and invoke start() twice
 
Paweł Baczyński
Bartender
Posts: 1831
33
Firefox Browser IntelliJ IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
leometal Chen wrote:singleton pattern and invoke start() twice

I don't see any singleton here.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic