主要練習了隊列數據結構,對象序列化和反序列化,多線程操作
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class QueueThreadDemp { public static StringQueue names; public static void main(String[] args) throws Exception { names=getQueueObj(); // 子線程循環隊列 new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(5000); names = QueueThreadDemp.getQueueObj(); System.out.println(names.toString()); } catch (Exception e) { e.printStackTrace(); } } } }).start(); // 讀取鍵盤輸入 InputStream is = System.in; InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while (true) { String name = br.readLine(); names.push(name); File file = new File("E:\\queue.txt"); FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(names); oos.close(); fos.close(); } } public static StringQueue getQueueObj() throws Exception { File file = new File("E:\\queue.txt"); if (file.exists() && file.length() > 0) { FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis); names = (StringQueue) ois.readObject(); ois.close(); fis.close(); } else { names = new StringQueue(5); } return names; } } //數組隊列 class 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; index++; } public void pop() { for (int i = 1; i < index; i++) { mNames[i - 1] = mNames[i]; } index = index - 1; } public String toString() { String mes = ""; for (String name : mNames) { mes += name + ","; } return mes; } }
效果: