关于多线程的一些知识点(四)——生产者消费者

我看的教程例子比较复杂,自己提取了一下,可能写的不太好

public class ProCsum{
    private static int ticket = 0;//这是临界资源
    private static boolean flag = false;//用于判断
    static ProCsum proCsum = new ProCsum();
    public static void main(String[] args) {
        Runnable proR = new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                while(ticket<6){
                    proCsum.produce();
                }       
            }
        };
        
        Runnable cumR = new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                
                while(ticket<6){
                    proCsum.consume();
                }
            }
        };
        
        Thread proTh = new Thread(proR);
        Thread cumPh = new Thread(cumR);
        
        cumPh.start();
        proTh.start();
        
    }
    
    public synchronized void produce(){
        if (flag) {
            //LiProductor.class.wait();
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        ++ticket;
        System.out.println("生产门票"+ticket+"号");
        flag = true;
        //LiProductor.class.notifyAll();
        this.notifyAll();
    }
    
    public synchronized void consume(){
        if (!flag) {
            try {
                //LiProductor.class.wait();
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.println("消费门票"+ticket+"号");
        flag = false;
        //LiProductor.class.notifyAll();
        this.notifyAll();
    }
}

运行结果:


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。