字符串模板
允許在字符串中使用占位符來動態(tài)替換變量的值鳖悠。這提供了一種更簡潔、更直觀的方式來構(gòu)建字符串檐春,避免了傳統(tǒng)的字符串拼接或格式化方法的復(fù)雜性顽聂。
基本使用說明:
String name = "Joan";
String info = STR."My name is \{name}";
assert info.equals("My name is Joan"); // true
同時(shí)支持多行模板和表達(dá)式
String sore = "20";
var json = STR."""
{
"user": "\{
// We only want to use the firstname
this.user.firstname()
}",
"sore : \{sore}
}
""";
Switch 增強(qiáng)
switch語句通過模式匹配功能得到了顯著增強(qiáng)肥惭。以下是一個(gè)具體的示例:
Object value = "Hello";
switch (value) {
case String s -> System.out.println(s.length()); // 匹配String類型,并獲取長度
case Integer i -> System.out.println(i * 2); // 匹配Integer類型紊搪,并乘以2
case null -> System.out.println("Value is null"); // 匹配null值
default -> System.out.println("Unknown type"); // 未知類型
}
這種模式匹配的方式比傳統(tǒng)的switch語句更加靈活和強(qiáng)大蜜葱,因?yàn)樗辉倬窒抻诤唵蔚恼麛?shù)或枚舉類型的匹配,而是可以匹配任何類型的對象耀石,并根據(jù)對象的類型執(zhí)行相應(yīng)的操作牵囤。
記錄模式
記錄模式是一種新的語言特性,允許我們定義簡潔且不可變的數(shù)據(jù)模型滞伟。它通過自動創(chuàng)建構(gòu)造函數(shù)揭鳞、getter 和 equals/hashCode 等方法來簡化數(shù)據(jù)對象的定義。
public record Person(String name, int age) {}
Person person = new Person("Alice",25);
System.out.println(person.name());
System.out.println(person.age());
虛擬線程
歷史版本中梆奈,JDK 中的每個(gè) java.lang.Thread 實(shí)例都是一個(gè)平臺線程野崇。平臺線程在底層操作系統(tǒng)線程上運(yùn)行 Java 代碼,并在代碼的整個(gè)生命周期內(nèi)捕獲操作系統(tǒng)線程亩钟。平臺線程的數(shù)量受限于操作系統(tǒng)線程的數(shù)量乓梨。
在 JDK 21 中引入的虛擬線程被設(shè)計(jì)成一種輕量級的線程模型钥弯,它可以更高效地執(zhí)行異步代碼,避免了傳統(tǒng)線程模型中線程的創(chuàng)建和銷毀開銷督禽,提供更高的并發(fā)性和更低的資源消耗。
//創(chuàng)建一個(gè)新的并且已啟動的虛擬線程
Thread thread = Thread.startVirtualThread(runnable);
//創(chuàng)建executor
ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
//通過executor提交任務(wù)总处,采用虛擬線程執(zhí)行
executor.submit(runnable);