NetBeans 4.0 Beta 2 + JDK 1.5,展示核心語法糖與 java.util.concurrent 並發包威力。
List<String> list = new ArrayList<String>();
list.add("1"); list.add("first");
for (String s : list) { System.out.println(s); } // 增強 for 迴圈
Vector v = new Vector();
v.add(23); // int → Integer 自動裝箱
for (int i : v) { System.out.println(i); } // Integer → int 自動拆箱
HashMap map = new HashMap();
map.put("key1", 23);
for (String key : map.keySet()) { System.out.println(key); }
import static test.Constants.FIRST;
System.out.println(FIRST); // 直接使用常數,無需類別前綴
System.out.printf("%2$s %1$d ", new Integer(1), "str"); // 輸出: str 1
public static enum FirstEnum { ONE, TWO }
for (FirstEnum fe : FirstEnum.values()) { System.out.println(fe); }
Executor exec = Executors.newFixedThreadPool(5);
for (int i = 0; i < 50; i++) {
exec.execute(new Runnable() {
public void run() {
int cur;
synchronized (lock) { cur = count++; }
System.out.println(cur + " running...");
try { Thread.sleep(2000); } catch (Exception e) { e.printStackTrace(); }
System.out.println(cur + " end...");
if (cur == 49) System.exit(0);
}
});
}
// 關閉鉤子
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() { System.out.println("program end."); }
});
亮點:ExecutorService 管理線程池,避免手動管理線程生命週期;shutdownHook 確保優雅關閉。
JDK 1.5 透過語法糖(泛型、枚舉、自動裝箱、靜態導入、增強 for、printf)大幅提升開發效率與程式碼可讀性;java.util.concurrent 提供工業級並發工具,徹底改寫多執行緒開發範式。