public class Box{
int index = 0;
sc[] arrWT = new sc[6];
public synchronized void push(sc wt) {
if(index == arrWT.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
arrWT[index] = wt;
index ++;
}
public synchronized sc pop() {
if(index == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
index --;
return arrWT[index];
}
}
package com.bank;
public class Consumer implements Runnable{
Box ss = null;
Consumer(Box ss) {
this.ss = ss;
}
public void run() {
for(int i=0; i<20; i++) {
sc wt= ss.pop();
//System.out.println(wt);
System.out.println("消费了:" +wt+"个产品");
try {
Thread.sleep((long) (Math.random()*1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.bank;
public class Producer implements Runnable{
Box ss = null;
Producer(Box ss) {
this.ss = ss;
}
public void run() {
for(int i=0; i<20; i++) {
sc wt= new sc(i);
ss.push(wt);
System.out.println("生产了:" + wt+"个产品");
try {
Thread.sleep((long) (Math.random()*200));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.bank;
public class Main {
public static void main(String[] args) {
Box ss = new Box();
Producer p = new Producer(ss);
Consumer c = new Consumer(ss);
new Thread(p).start();
new Thread(c).start();
}
}
class sc {
int id;
sc(int id) {
this.id = id;
}
public String toString() {
return "sc :" + id;
}
}