0

i have questions in java ,as the below code "name" is a reference and "name" value changed during thread running, my question is why "name" doesn't print "hello,oscar" the changed value?

public class MakeThread implements Runnable{
    String name;
    public  MakeThread(String name) {
     this.name=name;
    }
    @Override
    public void run() {
    try {
        System.out.println("i am going to sleep 10 sec");
        TimeUnit.SECONDS.sleep(10);
        System.out.println(Thread.currentThread().getName()+"name is:"+name);
    } catch (InterruptedException e) {          
        e.printStackTrace();
    }   
    }
}


public class TestRefer {    
    public static void main(String[] args) {
    String name=new String("hello,world");
    Runnable runnable=new MakeThread(name); 
    Thread thread2=new Thread(runnable);
    thread2.start();
    name= new String("hello, oscar");   
    System.out.println("TestRefer name " +name);
    }  
}

print results is :

TestRefer name:hello, oscar
i am going to sleep 10 sec
Thread-0 name is:hello,world
Oscar
  • 324
  • 1
  • 3
  • 11
  • I would not risk all that confusion and just use more different identifiers... – Yunnosch Jul 10 '18 at 06:01
  • `name` is a variable, and it contains a String reference. You have changed the reference `name` into another String instance. Your `println()` prints out the value of the new reference in `name` variable. – Jai Jul 10 '18 at 06:01

0 Answers0