手写阻塞队列,实现生产者和消费者的模式





wait()notify()方法 要和 synchronized 关键字配合,实现线程的交替运行:


public class DemoProConsume {
    public static LinkedList message = new LinkedList();

    public static void main(String[] args) throws InterruptedException {
        final CountDownLatchXs latch = new CountDownLatchXs(2);

        System.out.println("************************开始 手写阻塞队列,实现生产者和消费者模式");
        Thread t1= new Thread(new Runnable() {
            public void run() {
                try {
                    for(int j = 0; j < 6; j++){
                        produce(1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    latch.countDown();
                }
            }
        },"生产者");


        Thread t2= new Thread(new Runnable() {
            public void run() {

                try {
                    for(int j = 0; j < 6; j++){
                        consume();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    latch.countDown();
                }
            }
        },"消费者");


        t1.start();
        t2.start();
        latch.await();
        System.out.println("************************结束 手写阻塞队列,实现生产者和消费者模式");
    }

    //生产者
    public  static void produce(Integer msg) throws InterruptedException {
        synchronized (message){
            if(message.size()>10){
                message.wait();
            }
            
            message.offerLast(msg);
            System.out.println(Thread.currentThread().getName()+"      ***message.offerLast()="+msg+"   ****message.size()="+message.size());
            //唤醒消费者线程,消费者和生产者自己去竞争锁
            message.notifyAll();
        }

    }

    public static void consume() throws InterruptedException {
        synchronized (message){
            if(message.size()<=0){
                message.wait();
            }
            
            System.out.println(Thread.currentThread().getName()+"   ***message.pollFirst()="+message.pollFirst()+"   ****message.size()="+message.size());
            //唤醒生产者线程,消费者和生产者自己去竞争锁
            message.notifyAll();
        }

    }
}
发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章