博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【面试题】实现一个队列数据结构,并使用这个队列实现一个生产者消费者模式...
阅读量:4929 次
发布时间:2019-06-11

本文共 1892 字,大约阅读时间需要 6 分钟。

一、采用链表实现队列

public class MyQueue {    private class Node {        public Node before;        public Object data;        public Node after;        public Node(Node before, Object data, Node after) {            this.before = before;            this.data = data;            this.after = after;        }    }    /**     * 头节点     */    private Node head;    /**     * 尾节点     */    private Node tail;    public MyQueue() {        head = new Node(null, null, null);        tail = new Node(null, null, null);        head.after = tail;        tail.before = head;    }    /**     * 入队列     * @param o     */    public void push(Object o) {        Node n = new Node(null, o, null);        Node n1 = tail.before;        tail.before = n;        n1.after = n;        n.before = n1;        n.after = tail;    }    /**     * 出队列     * @return     */    public Object pop() {        Node after = head.after;        Node n = after.after;        head.after = n;        n.before = head;        return after;    }}

 

 

 二、使用队列实现生产者消费者模式

public class Producer implements Runnable {    private MyQueue queue;    public Producer(MyQueue queue) {        this.queue = queue;    }    @Override    public void run() {//        while(true) {//            queue.push(Math.random());//        }    }}public class Consumer implements Runnable {    private MyQueue queue;    public Consumer(MyQueue queue) {        this.queue = queue;    }    @Override    public void run() {//        while (true) {//            Object o = queue.pop();//        }    }}public class Main {    public static void main(String[] args) {        MyQueue queue = new MyQueue();        Producer producer = new Producer(queue);        Consumer consumer = new Consumer(queue);        Thread t1 = new Thread(producer);        Thread t2 = new Thread(consumer);        t1.start();        t2.start();    }}

 

转载于:https://www.cnblogs.com/jsnr-tdyd/p/8666423.html

你可能感兴趣的文章
cygwin daemon
查看>>
瀑布流
查看>>
前端规范
查看>>
Linux与Windows API对比
查看>>
CrossOriginFilter
查看>>
sequelize migration delete enum col and want that col back occur error
查看>>
使用sessionStorage获取值和设置值
查看>>
Nginx 反向代理的正确配置
查看>>
软件工程网络15个人作业3——案例分析
查看>>
hahacvf
查看>>
PV操作
查看>>
URL编码
查看>>
IOS 键盘的显示与关闭
查看>>
Oracle CASE WHEN 用法介绍
查看>>
300 Professional WordPress Themes Of 2012
查看>>
Java中String对象的创建
查看>>
【CentOS_7】安装nginx
查看>>
Android 启动模式--任务(Task)--桟 的误区
查看>>
CSS框架BluePrint
查看>>
hadoop_eclipse及HDT插件的使用
查看>>