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

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

作者: li_荔枝 | 来源:发表于2019-10-21 15:16 被阅读0次

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

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

相关文章

网友评论

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

      本文链接:https://www.haomeiwen.com/subject/oldzmctx.html