[多线程]-[机试题]-[生产者&消费者]


//自己的栈
class MyStack{
int[] max = null;
int index = 0;
public MyStack(int m){
max = new int[m];
}
public synchronized void push(int param){
//必须用while,被叫醒后,再检查一次
while(index>=max.length){
try {
System.out.println("栈已满 生产者WAIT===========================");
this.wait();
System.out.println("生产者 被notify");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
max[index] = param;
index ++ ;
}
public synchronized int pop(){
//必须用while,被叫醒后,再检查一次
while(index<=0){
try {
System.out.println("栈已空 消费者WAIT===========================");
this.wait();
System.out.println("消费者 被notify");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
index --;
return max[index];
}
}
//生产者
class Producer implements Runnable{
MyStack myStack = null;
int count;
public Producer(MyStack ms,int count){
myStack = ms;
this.count = count;
}
public void run(){
for(int i=1;i<=myStack.max.length;i++){
myStack.push(i);
System.out.println("第"+count+"个生产者,第"+i+"次生产:"+i);
try {
Thread.sleep((int)(Math.random()*300));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//消费者
class Consumer implements Runnable{
MyStack myStack = null;
int count;
int i;
public Consumer(MyStack ms,int count){
myStack = ms;
this.count = count;
}
public void run(){
for(int i=1;i<=myStack.max.length;i++){
int x = myStack.pop();
System.out.println("第"+count+"个消费者,第"+i+"次消费:"+x);
try {
Thread.sleep((int)(Math.random()*300));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//测试类
public class ProducerConsumerTest {

public static void main(String[] args) {
MyStack ms = new MyStack(10);
Thread p1 = new Thread(new Producer(ms,1));
Thread p2 = new Thread(new Producer(ms,2));
Thread p3 = new Thread(new Producer(ms,3));
Thread c1 = new Thread(new Consumer(ms,1));
Thread c2 = new Thread(new Consumer(ms,2));
p1.start();
p2.start();
p3.start();
c1.start();
c2.start();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值