Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.LinkedList;
- public class BlockingQueue<T> {
- private LinkedList<T> lista = new LinkedList<T>();
- private int maxNumber;
- public BlockingQueue()
- {
- maxNumber = -1;
- }
- public BlockingQueue(int max)
- {
- maxNumber = max;
- }
- public synchronized void offer(T e) throws InterruptedException
- {
- while(size() > maxNumber && maxNumber != -1)
- {
- wait();
- }
- lista.add(e);
- System.out.println("Meteu " + e.toString());
- notifyAll();
- }
- public synchronized T poll() throws InterruptedException
- {
- while(size() == 0)
- {
- wait();
- }
- T e = lista.pop();
- System.out.println("Retirou " + e.toString());
- notifyAll();
- return e;
- }
- public synchronized int size()
- {
- return lista.size();
- }
- public synchronized void clear()
- {
- lista.clear();
- notifyAll();
- }
- public static void main(String[] args) {
- Teste[] vetor = new Teste[10];
- BlockingQueue<Integer> lista =
- new BlockingQueue<Integer>(3);
- for(int i = 0; i< 10; i++)
- {
- vetor[i] = new Teste(lista, i%2==0);
- vetor[i].start();
- }
- }
- }
- class Teste extends Thread
- {
- private BlockingQueue<Integer> lista;
- private boolean consumer;
- public Teste(BlockingQueue<Integer> b, boolean c)
- {
- lista = b;
- consumer = c;
- }
- public void run()
- {
- for(int i = 0; i < 10; i++)
- {
- if(consumer)
- {
- try {
- Integer e = lista.poll();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- else
- {
- Integer inte = (int)(Math.random()*100);
- try {
- lista.offer(inte);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- try {
- sleep((int)(Math.random() * 1000));
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement