美文网首页JAVA技术文章
java并发之wait和notify

java并发之wait和notify

作者: rejoice001 | 来源:发表于2018-06-27 02:32 被阅读4次

2个窗口交替出售一张票,控制台可能会因为异步打印的原因出现连续打印一个窗口的票,但是票的奇偶肯定固定在一个窗口出售


public class WaitAndNodtify {
    
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        new Seller1(ticket).start();
        new Seller2(ticket).start();
    }
    static class Ticket{
        public Integer count = 1000;
        public Boolean isSeller1 = true;
        
    }
    
    static class Seller2 extends Thread{
        
        private Ticket ticket;
        
        Seller2(Ticket ticket){
            this.ticket = ticket;
        }
        
        @Override
        public void run() {
                while(ticket.count > 0) {
                    synchronized(ticket) {
                        if(ticket.isSeller1) {
                            try {
                                ticket.wait();
                            } catch (InterruptedException e) {
                            }
                        }
                        if(ticket.count <= 0) {
                            continue;
                        }
                        System.err.println("窗口2售第【 "+ticket.count+" 】张票");
                        ticket.count--;
                        ticket.isSeller1=true;
                        ticket.notify();
                    }
                }
        }
        
    }
    
    static class Seller1 extends Thread{
        
        private Ticket ticket;
        
        Seller1(Ticket ticket){
            this.ticket = ticket;
        }
        
        @Override
        public void run() {
                while(ticket.count > 0) {
                    synchronized(ticket) {
                        if(!ticket.isSeller1) {
                            try {
                                ticket.wait();
                            } catch (InterruptedException e) {
                            }
                        }
                        if(ticket.count <= 0) {
                            continue;
                        }
                        System.out.println("窗口1售第【 "+ticket.count+" 】张票");
                        ticket.count--;
                        ticket.isSeller1=false;
                        ticket.notify();
                    }
                }
        }
        
    }
}

运行结果

image.png

相关文章

网友评论

    本文标题:java并发之wait和notify

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