java 阻塞队列自定义实现


自定义阻塞队列:思路==》阻塞队列有这样一个特点,当队列中没有值得时候,这是只允许值得插入,当队列中有值得时候,这时候允许队列的插入,同时也允许队列中元素的移除,但是当队列中没有值得时候,这时候就不允许队列的移除了,而是等待其他线程插入新的元素
public class BlockingQueue {
     private LinkedListlist=new LinkedList<>();
     /**
      * 阻塞队列插入:一旦插入说明阻塞队列中有值,这是唤醒其他线程过来取
      *@parame
      */
     publicvoid push(E e){
          synchronized(list){
              list.add(e);
              list.notifyAll(); 
          }
     }
     /**
      * 如果链表中没有值,则所有线程进入到等待状态,知道有线程插入为止
      *@return
      */
     publicE poll(){
          synchronized(list){
              while(list.size()==0){
                   try{
                        list.wait();
                   }catch(InterruptedException e) {
                        e.printStackTrace();
                   }
              }
              E e =list.remove();
              returne;
          }
     }
}


利用自定义的阻塞队列实现生产者消费者
public class Test{ 
     public static void main(String[] args){ 
         ExecutorService exec = Executors.newCachedThreadPool(); 
         BlockingQueue queue =new BlockingQueue<>(); 
         exec.execute(newConsumer<>(queue)); 
         exec.execute(newProducer<>(queue, 1)); 
         exec.execute(newConsumer<>(queue)); 
         exec.execute(newProducer<>(queue, 2)); 
         exec.execute(newConsumer<>(queue)); 
         exec.execute(newProducer<>(queue, 3)); 
      
       } 
     
}
class Consumer implements Runnable { 
      private BlockingQueuequeue; 
      
      public Consumer(BlockingQueue queue) { 
        this.queue= queue; 
       } 
      
      @SuppressWarnings("unused") 
      @Override 
      public void run() { 
         E e =queue.poll(); 
         System.out.println("消费一个:"+e);
       } 
} 
      
      
class Producer implements Runnable { 
      private BlockingQueue queue; 
      private E e; 
      
      public Producer(BlockingQueue queue, E e) { 
        this.queue= queue; 
        this.e= e; 
       } 
      
      @Override 
      public void run() { 
        queue.push(e); 
         System.out.println("生产一个:"+e);
       } 
}


你可能感兴趣的:(面试题)