• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Calling run method directly

 
Ranch Hand
Posts: 145
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all !!

I have one problem with the following code :





Output : Hi Started
Hello Started

Problem:
How the Thread objects t1 and t2 are accessing the variable str.I think there should be compile error because of the following justification:

1)Here Thread object t1 is created which is directly accessing run method.
2)In run method str is accessed,which means this.str is accessed which in turn means str variable of t1 is accessed,but t1 object hasn't has str variable its the class exp has str variable.
3)So,how it is accessing variable str.

Please expalin.
[ August 22, 2004: Message edited by: Barry Gaunt ]
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The above code looks ok to me, since str is initialised in the constructor before the run method is called and t1, t2 each has it's own str variable.
 
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I hope you understand that the Threads created never start. The only Thread running is the one that executes main. Each instance of exp has its own copy of String str since it is declared as an instance variable.
Bill
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
For your query about accessing 'str' from the run method which is called by Thread objects t1 & t2 -
Remember that run method that you write is call back method which gets called by the run method of thread class.
Thread class could do it because you have registered your class with the thread (passed in the constructor of Thread class).
Look at the following code snippet to understand how Thread class might have implemented this feature.

 
These are not the droids you are looking for. Perhaps I can interest you in a tiny ad?
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic