1 package com.quadcap.util.threads; 2 3 40 41 import java.util.Vector ; 42 43 import com.quadcap.util.Debug; 44 import com.quadcap.util.DList; 45 import com.quadcap.util.DListItem; 46 import com.quadcap.util.ListException; 47 48 54 public class Stream { 55 int maxSize = 10; 56 DList queue = new DList(); 57 boolean full = false; 58 boolean closed = false; 59 60 63 public Stream() {} 64 65 70 public Stream(int maxSize) { 71 this.maxSize = maxSize; 72 } 73 74 79 public Object read() { 80 Object obj = null; 81 synchronized (queue) { 82 while (queue.size() == 0) { 83 if (closed) { 84 return new RuntimeException ("stream closed"); 85 } 86 try { 87 queue.wait(); 88 if (closed) throw new RuntimeException ("stream closed"); 89 } catch (InterruptedException e) { 90 Debug.print(e); 91 } 92 } 93 try { 94 DListItem d = queue.popFront(); 95 obj = d.obj; 96 } catch (ListException e) { 97 Debug.print(e); 98 } 99 if (full) { 100 full = false; 101 queue.notifyAll(); 102 } 103 } 104 return obj; 105 } 106 107 112 public void write(Object obj) { 113 synchronized (queue) { 114 while (queue.size() >= maxSize) { 115 if (closed) { 116 throw new RuntimeException ("stream closed"); 117 } 118 full = true; 119 try { 120 queue.wait(); 121 } catch (InterruptedException e) { 122 Debug.print(e); 123 } 124 } 125 queue.addBack(obj); 126 if (queue.size() == 1) queue.notifyAll(); 127 } 128 } 129 130 133 public void close() { 134 synchronized (queue) { 135 closed = true; 136 queue.notifyAll(); 137 } 138 } 139 } 140 | Popular Tags |