public class Test2 extends Object implements Runnable { 
   String s1 = "Earth "; 
   String s2 = "Moon"; 
   public void run() { 
     synchronized (s1) { 
//可以替换成synchronized(this),或synchronized(“hi”)
       for (int i=0; i < 2; i++) { 
        s1.concat(" to Moon "); 
        System.out.print(s1); 
        s2.concat(" to Earth "); 
        System.out.println(s2); 
       } 
     } 
   } 
  public static void main(String[] args) { 
     Test2 t = new Test2(); 
     new Thread(t).start(); 
     new Thread(t).start(); 
  } 

为什么输出:
Earth Moon
Earth Moon
Earth Moon
Earth Moon s2.concat(" to Earth "); 
        System.out.println(s2); 
 
输出为什么不是Moon Earth s1.concat(" to Moon "); 
        System.out.print(s1); 
        s2.concat(" to Earth "); 
        System.out.println(s2); 
为什么不是Moon to Earth

解决方案 »

  1.   

    String是final的,不可变
    改成s1=s1.concat(" to Moon "); 就知道了
      

  2.   

    改了以后,答案是:
    Earth  to Moon Moon to Earth 
    Earth  to Moon  to Moon Moon to Earth  to Earth 
    Earth  to Moon  to Moon  to Moon Moon to Earth  to Earth  to Earth 
    Earth  to Moon  to Moon  to Moon  to Moon Moon to Earth  to Earth  to Earth  to Earth 
    但我还是不明白
           s1.concat(" to Moon "); 
            System.out.print(s1); 
            s2.concat(" to Earth "); 
            System.out.println(s2); 的输出为什么是
    Earth Moon
    Earth Moon
    Earth Moon
    Earth Moon 
    在执行s1.concat(" to Moon "); 
            System.out.print(s1); 
            s2.concat(" to Earth "); 
            System.out.println(s2);的时候,s1,s2都不改变么
      

  3.   

    concat
    public String concat(String str)将指定字符串联到此字符串的结尾。 
    如果参数字符串的长度为 0,则返回此 String 对象。否则,创建一个新的 String 对象,用来表示由此 String 对象表示的字符序列和由参数字符串表示的字符序列串联而成的字符序列。示例:  "cares".concat("s") returns "caress"
     "to".concat("get").concat("her") returns "together"
     
    参数:
    str - 串联到此 String 结尾的 String。 
    返回:
    一个字符串,它表示此对象的字符后面串联字符串参数的字符
    ——————————————————————-——————————--
    看清楚上面的方法说明,concat 是有返回的是一个String 
    表示由此 String 对象表示的字符序列和由参数字符串表示的字符序列串联而成的字符序列。
    s1.concat(" to Moon "); 
            System.out.print(s1); 
            s2.concat(" to Earth "); 
            System.out.println(s2); 的输出为什么是
    Earth Moon
    Earth Moon
    Earth Moon
    Earth Moon 
    在执行s1.concat(" to Moon "); 
            System.out.print(s1); 
            s2.concat(" to Earth "); 
            System.out.println(s2);的时候,s1,s2都不改变么在看看你的第一句s1.concat(" to Moon "); 这时这个追加处理好的返回值你放那里?
    你根本没拿出来用。该写成s1=s1.concat(" to Moon "); 即给s1重新给个新地址。这样System.out.print(s1); 
    才显示出来