Sunday, 13 September 2015

getName() vs Thread.currentThread().getName()

package com.threads.status;
public class SynchThread extends Thread {
       SynchThread st;
       SynchThread(SynchThread s) {
              st = s;
       public void run(){

       synchronized void show(){
          for(int i=0;i<5;i++) 
                              //replacing line
              System.out.print(Thread.currentThread().getName()+" ");

       public static void main(String[] args) {
              SynchThread s1 = new SynchThread();

              Thread t1 = new SynchThread(s1);
              Thread t2 = new SynchThread(s1);




Output: t1 t1 t1 t1 t1 t2 t2 t2 t2 t2

When replacing line:
System.out.print(Thread.currentThread().getName()+" ");

Output: t0 t0 t0 t0 t0 t0 t0 t0 t0 t0

Because Thread.currentThread().getName() gets you the name of the currently-running thread, but getName() resolves to st.getName(), and st is always your first thread instance.

Why does getName() resolve to st.getName()?

1. During construction of your second through fourth threads, you pass the first thread in as an argument and save it in the instance member st.

2. The run method of your threads calls, so they're always calling show on the first thread. (If you ever started the first thread, you'd get an NPE there, since the first thread's st member is never given a non-null value.)

3. Within show, this is therefore st (the first thread). Unqualified instance method calls use this as their instance, and this is the first thread.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...