java线程同步(生产者消费者应用-模拟叫号系统)

执行结果:

顾客取得:票据0
票据0:顾客请到窗口11
顾客取得:票据1
票据1:顾客请到窗口10
顾客取得:票据2
票据2:顾客请到窗口11
顾客取得:票据3
票据3:顾客请到窗口10
顾客取得:票据4
票据4:顾客请到窗口11
顾客取得:票据5
票据5:顾客请到窗口10
顾客取得:票据6
票据6:顾客请到窗口11
顾客取得:票据7
票据7:顾客请到窗口10

票据类-写法一:

public class Titckets {
    Stack<Integer> tickets = new Stack<Integer>();


    public synchronized void getTicket() {
while (tickets.size() ==0) {//用while不用if保证遇到异常时仍能连续验证是不是为空
   try {
   this.wait();
} catch (InterruptedException e) {
   e.printStackTrace();
}
}
notifyAll();//先唤醒其他等待本对象锁的线程,然后自己再让出对象锁,唤醒其他线程语句执行后当前线程不会立即结束,直到同步块代码执行完才让出对象锁
System.out.println("票据" + tickets.pop() + ":顾客请到窗口"
   + Thread.currentThread().getId());


    }


    public synchronized void setTicket(int i) {
while (tickets.size()==10) {//如果等待人数超过10则停止出号,//用while不用if保证遇到异常时仍能连续验证是不是已满
   try {
   this.wait();
} catch (InterruptedException e) {
   e.printStackTrace();
}
}
notifyAll();//先唤醒其他等待本对象锁的线程,然后自己再让出对象锁
tickets.push(i);
   System.out.println("顾客取得:票据" + i);
    }
}

票据类-写法二:

public class Titckets {

    Stack<Integer> tickets = new Stack<Integer>();
    public synchronized void getTicket() {
if (tickets.size() > 0) {
   System.out.println("票据" + tickets.pop() + ":顾客请到窗口"
   + Thread.currentThread().getId());
}
notifyAll();//先唤醒其他等待本对象锁的线程,然后自己再让出对象锁
try {
   this.wait();
} catch (InterruptedException e) {
   e.printStackTrace();
}
    }
    public synchronized void setTicket(int i) {
if (tickets.size() < 10) {//如果等待人数超过10则停止出号
   tickets.push(i);
   System.out.println("顾客取得:票据" + i);
}
notifyAll();//先唤醒其他等待本对象锁的线程,然后自己再让出对象锁
try {
   this.wait();
} catch (InterruptedException e) {
   e.printStackTrace();
}
    }

}

取号线程类:

public class Producer implements Runnable {
    private Titckets titckets;
    public void run() {
for (int j = 0; j < 100; j++) {
    titckets.setTicket(j);
   }
    }
    public Producer(Titckets t) {
titckets = t;
    }
}

服务窗口类:

public class Custome implements Runnable {
    private Titckets titckets;
    public void run() {
for (int j = 0; j < 1000; j++) {
    titckets.getTicket();
}
    }
    public Custome(Titckets t) {
titckets = t;
    }
}

主线程:

public class GetAndSet {
    public static void main(String[] args) {
Titckets t = new Titckets();
new Thread(new Producer(t)).start();// 叫号线程
new Thread(new Custome(t)).start();// 窗口1服务线程
new Thread(new Custome(t)).start();// 窗口2服务线程
new Thread(new Custome(t)).start();// 窗口3服务线程
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值