一、题目
// 实现一个单例队列容器,提供三个方法 offer,poll,size
// 写三个线程,
// 线程1将字符串a每隔1s挨个添加到容器中,
// 线程2将字符串b每隔1s挨个添加到容器中,
// 线程1与线程2交替执行
// 线程3监听容器变化,调用poll每隔1s挨个输出
// 示例:
// 输入:a = “hloaiaa”, b = “el,lbb”
// 输出:hello,alibaba
public class Queue {
// Node
private class Node {
private char val;
private Node next;
public Node(char val, Node next) {
this.val = val;
this.next = next;
}
// setter and getter
// ....
}
// Singleton
public static enum SingletonEnum {
SINGLETON;
private final Queue instance;
private SingletonEnum() {
instance = new Queue();
}
public Queue getInstance() {
return instance;
}
}
private Node rear, front;
private int size;
// constructor
private Queue() {
this.rear = null;
this.front = null;
this.size = 0;
}
// poll
public char poll() {
if (this.front == null) {
throw new NullPointerException("Queue is empty");
}
Node node = this.front;
this.front = node.next;
if (this.front == null) this.rear = null;
this.size--;
return node.val;
}
// offer
public boolean offer(char val) {
Node node = new Node(val, null);
if (this.rear == null) {
this.front = node;
} else {
this.rear.next = node;
}
this.rear = node;
this.size++;
return true;
}
// size
public int size() {
return this.size;
}
}