欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java单线程实现队列模型

程序员文章站 2022-06-07 16:28:53
...
以下是我整理的用java单线程实现队列Queue的代码模型。

package com.cuishen;

import java.util.Vector;

public class Queue implements Runnable {
    private Vector queueData = null;
    private boolean run = true;

    public Queue() {
        queueData = new Vector();
    }

    public synchronized void putEvent(Object obj) {
        queueData.addElement(obj);
        notify();
    }

    private synchronized Object getEvent() {
        try {
            return (Object) queueData.remove(0);
        } catch (ArrayIndexOutOfBoundsException aEx) {
        }
        try {
            wait();
        } catch (InterruptedException e) {
            if (run) {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void run() {
        while (run) {
            Object obj = getEvent();
            processEvent(obj);
        }
    }

    private void processEvent(Object obj) {
        // process the data in queue
    }

    public synchronized void destroy() {
        run = false;
        queueData = null;
        notify();
    }
}


package com.cuishen;

public class Test {
    public static void main(String[] args) {
        Queue queue = new Queue();
        Thread processThread = new Thread(queue);
        processThread.start();
        
        Object obj = new Object();
        queue.putEvent(obj);
    }
}