1. 程式人生 > >生產者和消費者多執行緒模擬

生產者和消費者多執行緒模擬

package yn.ngems.cn;
class Message{
    private String title;
    private String content;
    private boolean flag = true;//true,生產,不消費;false,消費,不生產
    public synchronized void set(String title,String content) {
        if(this.flag == false) {
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.title = title;
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.content = content;
        this.flag = false;
        super.notify();
    }
    public synchronized String get() {
        if(this.flag == true) {
            try {
                super.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            return this.title + "  --  " + this.content;
        }finally {
            this.flag = true;
            super.notify();
        }
    }
}
class Productor implements Runnable{
    private Message msg;
    public Productor(Message msg) {
        this.msg = msg;
    }
    @Override
    public void run() {
        for(int x = 0;x < 50;x ++) {
            if(x % 2 == 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                this.msg.set("AAA", "aaa");
            }else {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                this.msg.set("BBBB", "bbbbbbbb");
            }
        }
    }
}
class Consumer implements Runnable{
    private Message msg;
    public Consumer(Message msg) {
        this.msg = msg;
    }
    @Override
    public void run() {
        for(int x = 0;x < 50;x ++) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(this.msg.get());
        }
    }
}
public class ThreadDemo {
    public static void main(String[] args) {
        Message msg = new Message();
        new Thread(new Productor(msg)).start();
        new Thread(new Consumer(msg)).start();
    }
}
思路:Message類是生產者和消費者的連結,從初次的簡單Java類來做,會出現很多問題,一步步分析,資料是否同步,鎖機制,生產和消費不能同時進行,需要有等待,設定開關進行等待判斷和喚醒,增加休眠時間,為了更好的展現問題所在。