java——多线程

一、题目

// 实现一个单例队列容器,提供三个方法 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;
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值