This week's book giveaway is in the Testing forum.
We're giving away four copies of Data Structures the Fun Way: An Amusing Adventure with Coffee-Filled Examples and have Jeremy Kubica on-line!
See this thread for details.
  • 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
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

Thread doubt

 
Ranch Hand
Posts: 383
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What will happen when you attempt to compile and run the following code.

public class Pmason implements Runnable{
static String a;
public static void main(String argv[]){
Pmason pm = new Pmason();
}
Pmason(){
a="alpha";
Thread t = new Thread(this);
t.start();
Thread t1 = new Thread(this);
a="zebra";
t1.start();
}
public void run(){
for(int i=0; i < 5; i ++){
System.out.println(a);
}

}
}


Select 1 option


1) Compilation without error, but the exact output cannot be determined.-answer 2) Compile time error, static string a cannot be accessed in a non static context.
3) Compilation and out put of alpha five times followed by output of zebra five times.
4) Compile time error, the implicit this reference is not available within a constructor.

Why it compile? Why Thread takes (this) reference? Can anyone explain?
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Dolly,

Every thread object requires, a Runnable instance to start a new thread of execution. In our case Pmason is implementing Runnable interface and the two thread objects are instantiated from with in Pmasaon class and hence thisrepresenting the current Runnable object is used to refer the current object while creating the Thread object. I hope I didn't confuse you more
 
No matter how many women are assigned to the project, a pregnancy takes nine months. Much longer than this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic