java多線程——生產者和消費者

使用同步方法來保證數據的一致性,使用wait() 和 notify() 、notifyAll()方法來解決重複操作。


public class Test {
    public static void main(String[] args) {
        Message msg = new Message();
        Producer producer = new Producer(msg);
        Consumer consumer = new Consumer(msg);
        new Thread(producer,"producer").start();
        new Thread(consumer, "consumer").start();
    }
}
class Producer implements Runnable {
    private Message msg;

    public Producer(Message msg) {
        this.msg = msg;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {

            if (i % 2 == 0) {
                this.msg.set("小明-", "第一帥哥");
            } else {
                this.msg.set("小qiang-", "第一猥瑣男");
            }
        }
    }
}

class Consumer implements Runnable {
    private Message msg;

    public Consumer(Message msg) {
        this.msg = msg;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {

            System.out.println(this.msg.get());
        }

    }
}

class Message {
    private String title;
    private String content;
    private boolean flag;
    // flag = true; 允許生產,禁止消費
    // flag = false; 允許消費,禁止生產
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public synchronized void set(String titile, String content) {

        if (!this.flag) {
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.title = titile;
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.content = content;
        this.flag = false;
        super.notify();
    }
    public synchronized String get() {
        if (this.flag) {
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            return this.title + this.content;
        } finally {
            this.flag = false;
            super.notify();
        }

    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章