生产者消费者之 wait / notify

package com.wjxie.wait.notify;

public class Producer extends Thread {

    public Producer(String name) {
        super(name);
    }

    @Override
    public void run() {
        while (true) {
            synchronized (Main.queue) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }

                if (Main.queue.size() == Main.MAX_SIZE) {
                    try {
                        Main.queue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    Item item = new Item();
                    Main.queue.offer(item);
                    // 生产一次之后,立马释放锁。一方面让消费者消费,另一方面让其他生产者生产。
                    Main.queue.notify();
                    System.out.println(this.getName() + " produce " + item);
                }
            }
        }
    }

}



package com.wjxie.wait.notify;

public class Consumer extends Thread {

    public Consumer(String name) {
        super(name);
    }

    @Override
    public void run() {
        while (true) {
            synchronized (Main.queue) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }

                if (Main.queue.size() == 0) {
                    try {
                        Main.queue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    Item item = Main.queue.poll();
                    // 消费一次之后,立马释放锁。一方面让生产者生产,另一方面让其他消费者消费。
                    Main.queue.notify();
                    System.out.println(this.getName() + " consume " + item);
                }
            }
        }
    }

}



package com.wjxie.wait.notify;

import java.util.LinkedList;
import java.util.Queue;

public class Main {

    // 最大容量
    public static final int MAX_SIZE = 100;
    // 容器,兼作排它锁
    public static Queue<Item> queue = new LinkedList<Item>();

    public static void main(String[] args) {
        Thread p = new Producer("[P]");
        Thread p2 = new Producer("[P2]");
        Thread c = new Consumer("[C]");
        Thread c2 = new Consumer("[C2]");
        p.start();
        p2.start();
        c.start();
        c2.start();
    }

}



package com.wjxie.wait.notify;

public class Item {

    private int id;

    public Item() {
        id = ID.getID();
    }

    @Override
    public String toString() {
        return "Item[" + id + "]";
    }

    static class ID {

        private static int id = 0;

        public static int getID() {
            return ++id;
        }

    }

}

猜你喜欢

转载自dsxwjhf.iteye.com/blog/2241357