以生产和消费馒头为例。
馒头实例
package relation;
public class ManTou {
public int id;
public ManTou(int id) {
this.id = id;
}
@Override
public String toString() {
return "ManTou{" +
"id=" + id +
'}';
}
}
存取馒头的实例
package relation;
public class SyncStack {
public int index;
public ManTou[] manTous = new ManTou[6];
public synchronized void push(ManTou manTou){
while (manTous.length == index){
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
this.notify();
manTous[index] = manTou;
index++;
}
public synchronized ManTou pop(){
while (index == 0){
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
this.notify();
ManTou manTou = manTous[index-1];
index--;
return manTou;
}
}
生产者实例
package relation;
public class Producer extends Thread{
SyncStack syncStack;
public Producer(SyncStack syncStack){
this.syncStack = syncStack;
}
public void run(){
for (int i = 0; i < 20; i++){
ManTou manTou = new ManTou(i);
this.syncStack.push(manTou);
System.out.println("我生产了馒头:" + manTou);
try {
Thread.sleep((long) (1000*Math.random()));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
消费者实例
package relation;
public class Consumer extends Thread{
public SyncStack syncStack;
public Consumer(SyncStack syncStack){
this.syncStack = syncStack;
}
public void run(){
for (int i = 0; i < 20; i++){
ManTou manTou = syncStack.pop();
System.out.println("我取出馒头:" + manTou);
try {
Thread.sleep((long) (1000 * Math.random()));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
实现实例
package relation;
public class Demo {
public static void main(String[] args) {
SyncStack syncStack = new SyncStack();
Producer producer = new Producer(syncStack);
Consumer consumer = new Consumer(syncStack);
producer.start();
consumer.start();
}
}