生产者和消费者多线程模拟

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类来做,会出现很多问题,一步步分析,数据是否同步,锁机制,生产和消费不能同时进行,需要有等待,设置开关进行等待判断和唤醒,增加休眠时间,为了更好的展现问题所在。

猜你喜欢

转载自blog.csdn.net/qq_27347147/article/details/84779269