參考:http://blog.csdn.net/yasi_xi/article/details/25482173
學習多線程的時候實例化線程數組而挖掘出來的一直以來的理解誤區
之前一直以為for each 本質上和for循環以及迭代器沒什么區別
?
1 package foreach; 2 3 public class ForeachDemo1 { 4 5 public static void main(String[] args) { 6 Object[] objs = new Test[5]; 7 int i = 0; 8 //for each的簡潔使得我喜歡這種使用方式 9 for(Object obj : objs) { 10 obj = new Test(i + ""); 11 System.out.println(objs[i++]);//2 12 } 13 System.out.println(objs[2]);//1 14 } 15 16 } 17 18 class Test { 19 20 private String value; 21 22 public Test(String value) { 23 this.value = value; 24 } 25 26 public String getValue() { 27 return value; 28 } 29 30 public void setValue(String value) { 31 this.value = value; 32 } 33 34 @Override 35 public String toString() { 36 return "Test [value=" + value + "]"; 37 } 38 39 40 41 }
打印的結果使得我很是懵逼
后來查了下資料才知道for each內部的大概實現方式
有趣的是,這個砸到我頭的蘋果是這樣的..
1 package foreach; 2 3 public class Apple1 { 4 5 public static void main(String[] args) { 6 Thread[] t1 = new T1[3]; 7 Thread[] t2 = new T2[2]; 8 9 for(Thread t : t1) { 10 t = new T2();//大概就是這樣,原代碼是生產者消費者交替打印而產生的線程無限等待 11 //然而這樣做并沒毛病 12 //-->等價于 13 //Thread t = t1[0] 14 //t = new T2() 15 //t.start() 16 //這當然沒問題了 17 t.start(); 18 } 19 20 t1[0] = new T2(); 21 //但是這樣的話 就拋異常了【當你試圖將錯誤類型的對象存儲到一個對象數組時拋出的異常】 22 //聲明的空間和實際new的類型不一致 23 } 24 25 } 26 27 class T1 extends Thread { 28 29 //... 30 31 @Override 32 public void run() { 33 // TODO Auto-generated method stub 34 } 35 36 } 37 38 class T2 extends Thread { 39 40 //.. 41 42 @Override 43 public void run() { 44 // TODO Auto-generated method stub 45 } 46 47 }
驗證:
1 package foreach; 2 3 public class Demo2 { 4 5 public static void main(String[] args) { 6 String[] strs = new String[3]; 7 8 for(String s : strs) { 9 s = "1"; 10 } 11 12 System.out.println(strs[0]); 13 } 14 15 }
?