java 双端队列 Deque

 

 

简单的实现生产者消费者模式。

package com.citi.test.mutiplethread.demo0503;

import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.LinkedBlockingDeque;

public class ProducerDeque implements Runnable{
    private LinkedBlockingDeque<String> deque;
    
    public ProducerDeque(LinkedBlockingDeque<String> deque) {
        this.deque=deque;
    }

    @Override
    public void run() {
        while(true){
            try {
                String str=UUID.randomUUID().toString();
                System.out.println(Thread.currentThread().getName()+"生产了:"+str);
                deque.putFirst(str);
                System.out.println(Thread.currentThread().getName()+"生产了:"+Arrays.toString(deque.toArray()));
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}
package com.citi.test.mutiplethread.demo0503;

import java.util.concurrent.LinkedBlockingDeque;

public class ConsumerDeque implements Runnable{

    private LinkedBlockingDeque<String> deque;
    public ConsumerDeque(LinkedBlockingDeque<String> deque) {
        this.deque = deque;
    }

    @Override
    public void run() {
        while(true){
            try {
                System.out.println(Thread.currentThread().getName()+"消费了:"+deque.takeLast());
                Thread.sleep(800);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
    }

}
package com.citi.test.mutiplethread.demo0503;

import java.util.concurrent.LinkedBlockingDeque;

public class LinkedBlockingDequeTest {
    public static void main(String[] args) {
        LinkedBlockingDeque<String> producerDeque=new LinkedBlockingDeque<String>();
        
        new Thread(new ProducerDeque(producerDeque)).start();
        new Thread(new ProducerDeque(producerDeque)).start();
        new Thread(new ProducerDeque(producerDeque)).start();
        new Thread(new ProducerDeque(producerDeque)).start();
        
        new Thread(new ConsumerDeque(producerDeque)).start();
    }
}

 

posted @ 2019-09-25 21:27  泥古拉斯赵四  阅读(451)  评论(0编辑  收藏  举报