java单线程实现队列模型
程序员文章站
2022-06-07 16:29:59
...
以下是我整理的用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); } }