Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Threads-Id  RSS feed

 
kalpita lawande
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
In scjp6 kathy Sierra and Bert Bates ,there is an question in exercise which i am not able to understand.

public class Starter implements Runnable{
void go(long id){
System.out.println(id);
}

public static void main(String[] args){
System.out.print(Thread.currentThread().getId()+" ");
//insert code here
}
public void run(){go(Thread.currentThread().getId());}
}

given are 5 fragments:
1.new Starter().run();
2.new Starter().start();
3.new Thread(new Starter());
4.new Thread(new Starter()).run();
5.new Thread(new Starter()).start();

Ans:One produce output 4 2,exactly two produce output 4 4

I am confused with this answer as i am not able to understand how id is 4 2 and 4 4.
I would be grateful if anyone could help me.

thanks
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The key isn't to know that the ids are 4 2, or 4 4. It is that in two cases, the same Thread ID is printed out (in the example, the ID happens to be 4) and in one case different Thread IDs were printed out (in the example, the IDs happen to be 4 and 2).

So, when the printed IDs are the same, what does that mean? When would the print statement inside the go() method print the same output as the print statement inside the main() method?

When the printed IDs are different, what does that mean? When would the print statement inside the go() method print different output from the one inside the main() method?

Which, do you think, is the intended behavior?

Without writing code (but use java.lang.Thread api if you want) can you figure out which one(s) produce each output, and figure out what output the other 2 options would print out?


kalpita lawande wrote:Hi,
In scjp6 kathy Sierra and Bert Bates ,there is an question in exercise which i am not able to understand.

public class Starter implements Runnable{
void go(long id){
System.out.println(id);
}

public static void main(String[] args){
System.out.print(Thread.currentThread().getId()+" ");
//insert code here
}
public void run(){go(Thread.currentThread().getId());}
}

given are 5 fragments:
1.new Starter().run();
2.new Starter().start();
3.new Thread(new Starter());
4.new Thread(new Starter()).run();
5.new Thread(new Starter()).start();

Ans:One produce output 4 2,exactly two produce output 4 4

I am confused with this answer as i am not able to understand how id is 4 2 and 4 4.
I would be grateful if anyone could help me.

thanks
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!