多线程复习

 1 public   class  MyStack  {
 2    private int[] a;
 3    private int count = 0;
 4    public final int MAX_SIZE;
 5
 6    public MyStack(int size) {
 7        MAX_SIZE = size;
 8        a = new int[size];
 9        count = 0;
10    }

11
12    public synchronized void push() {
13         while(count==MAX_SIZE){//这里用while而不是if因为当被唤醒时,该线程处于锁池等待获取锁,这个时候可能会有别的该线改变数组的大小。所以唤醒时继续检查数组是否已满。
14             try {
15                this.wait(); //释放掉当前的对象锁,在等待池等待
16            }
 catch (InterruptedException e) {
17                e.printStackTrace();
18            }

19         }

20         a[count++]=count;
21         System.out.println(Thread.currentThread().getName()+"压入数据:"+count);
22         this.notify();  //唤醒生产者消费者线程
23    }

24
25    public synchronized int pop() {
26             while(count ==0){
27                 try {
28                    this.wait();
29                }
 catch (InterruptedException e) {
30                    e.printStackTrace();
31                }

32             }

33             this.notify();
34             System.out.println(Thread.currentThread().getName()+"弹出数据:"+count);
35             return a[--count];
36     }

37}

38 /** */ /**
39 *生产者
40 **/

41 public   class  Producer  extends  Thread  {
42
43    private MyStack stack;
44    
45    public Producer(MyStack stack){
46        this.stack = stack;
47    }

48    @Override
49    public void run() {
50        while (true{
51            stack.push();
52            try {
53                Thread.sleep(200);
54            }
 catch (InterruptedException e) {
55                e.printStackTrace();
56            }

57        }

58    }

59}

60 /** */ /**
61 *消费者
62 **/

63 public   class  Consumer  extends  Thread {
64             
65    private MyStack stack;
66    
67    public Consumer(MyStack stack){
68        this.stack = stack;
69    }

70    
71    @Override
72    public void run() {
73        while(true){
74            stack.pop();
75            try {
76                Thread.sleep(300);
77            }
 catch (InterruptedException e) {
78                e.printStackTrace();
79            }

80        }

81    }

82}

线程状态图
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值