|
133 | 133 | lock.unlock();
|
134 | 134 | }
|
135 | 135 | }
|
136 |
| -``` |
| 136 | +``` |
| 137 | + |
| 138 | +## Test |
| 139 | +* Producer |
| 140 | +Producer continuously put data into queue. |
| 141 | +```Java |
| 142 | +public class ArrayBlockingQueueProducer implements Runnable { |
| 143 | + private ArrayBlockingQueue<Integer> queue; |
| 144 | + public ArrayBlockingQueueProducer(ArrayBlockingQueue<Integer> queue) { |
| 145 | + super(); |
| 146 | + this.queue = queue; |
| 147 | + } |
| 148 | + private volatile AtomicInteger ai = new AtomicInteger(0); |
| 149 | + @Override |
| 150 | + public void run() { |
| 151 | + while(true){ |
| 152 | + try { |
| 153 | + queue.put(ai.getAndIncrement()); |
| 154 | + System.out.println("Producer: put " + ai.get() + " into queue..."); |
| 155 | + Thread.sleep(10); |
| 156 | + } catch (InterruptedException e) { |
| 157 | + e.printStackTrace(); |
| 158 | + } |
| 159 | + } |
| 160 | + } |
| 161 | +} |
| 162 | +``` |
| 163 | + |
| 164 | +* Consumer |
| 165 | +Consumer get take data from queue 100 times |
| 166 | +```Java |
| 167 | +public class ArrayBlockingQueueConsumer implements Runnable { |
| 168 | + private ArrayBlockingQueue<Integer> queue; |
| 169 | + public ArrayBlockingQueueConsumer(ArrayBlockingQueue<Integer> queue) { |
| 170 | + super(); |
| 171 | + this.queue = queue; |
| 172 | + } |
| 173 | + @Override |
| 174 | + public void run() { |
| 175 | + try { |
| 176 | + for(int i = 0; i < 100; i++){ |
| 177 | + Thread.currentThread().join(10); |
| 178 | + System.out.println("Consumer: get " + queue.take() + " from queue..."); |
| 179 | + Thread.sleep(10); |
| 180 | + } |
| 181 | + } catch (InterruptedException e) { |
| 182 | + e.printStackTrace(); |
| 183 | + } |
| 184 | + } |
| 185 | + |
| 186 | + public static void main(String[] args) throws InterruptedException { |
| 187 | + ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10); |
| 188 | + new Thread(new ArrayBlockingQueueConsumer(queue)).start(); |
| 189 | + new Thread(new ArrayBlockingQueueProducer(queue)).start(); |
| 190 | + Thread.currentThread().join(); |
| 191 | + System.out.println("Finish..."); |
| 192 | + } |
| 193 | +} |
| 194 | +``` |
| 195 | +* Result |
| 196 | +>... |
| 197 | +Producer: put 108 into queue... |
| 198 | +Consumer: get 98 from queue... |
| 199 | +Producer: put 109 into queue... |
| 200 | +Consumer: get 99 from queue... |
| 201 | +Producer: put 110 into queue... |
| 202 | + |
| 203 | +We can find that Producer is **blocked**. |
0 commit comments