本示例演示如何結合數組實現的循環隊列、對象序列化持久化、多線程定時讀取與控制台交互輸入,構建一個簡單的名稱管理控制台程序。
push(滿時自動移除最舊)和 pop 操作ObjectOutputStream/ObjectInputStream 將隊列對象存儲至文件 E:\queue.txtclass StringQueue implements Serializable {
private String[] mNames;
private int index = 0;
private int nums;
public StringQueue(int nums) {
mNames = new String[nums];
this.nums = nums;
}
public void push(String name) {
if (index >= nums) pop(); // 滿時移除最舊
mNames[index++] = name;
}
public void pop() {
for (int i = 1; i < index; i++) mNames[i-1] = mNames[i];
index--;
}
public String toString() {
String mes = "";
for (String name : mNames) mes += name + ",";
return mes;
}
}
public static void main(String[] args) throws Exception {
names = getQueueObj(); // 啟動時加載持久化數據
// 子線程:定時刷新並打印
new Thread(() -> {
while (true) {
try {
Thread.sleep(5000);
names = getQueueObj();
System.out.println(names);
} catch (Exception e) { e.printStackTrace(); }
}
}).start();
// 主線程:讀取控制台輸入
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String name = br.readLine();
names.push(name);
// 序列化保存
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("E:\\queue.txt"));
oos.writeObject(names);
oos.close();
}
}

| 知識點 | 應用場景 |
|---|---|
| 數組循環隊列 | 固定容量、先進先出、自動覆蓋舊數據 |
| 對象序列化 | 實現 Serializable、ObjectOutputStream/InputStream 文件持久化 |
| 多線程協作 | Thread + Runnable、sleep 定時任務、主線程阻塞 IO |
| 文件操作 | File、FileOutputStream、FileInputStream 基礎 IO 流鏈 |
ArrayDeque 替代手寫隊列,線程安全版用 ConcurrentLinkedQueueSystem.out.printlntry-with-resources 寫法