//自己的栈
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();
}
}
[多线程]-[机试题]-[生产者&消费者]
最新推荐文章于 2023-06-28 20:41:45 发布