你的位置:首页 > Java教程

[Java教程][javaSE] 练习队列线程和对象序列化


主要练习了队列数据结构,对象序列化和反序列化,多线程操作

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;  }}

效果: