package com.gdut.lang.thread;
public class ProducerAndConsumer {
public static void main(String[] args) {
SyncStack ss = new SyncStack();
Producer p = new Producer(ss);
Consumer c = new Consumer(ss);
new Thread(p).start();
new Thread(c).start();
}
}
class WoTou {
private int id;
public WoTou(int id) {
this.id = id;
}
public String toString() {
return "WoTou : " + id;
}
}
class SyncStack {
int index = 0;
WoTou[] arrWT = new WoTou[5];
public synchronized void push(WoTou wt) {
if ( index == arrWT.length ) { //窝头数组满了
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
arrWT[index] = wt;
index++;
this.notify();
}
public synchronized WoTou pop() {
if ( index == 0 ) { //数组里面没窝头了
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
index--;
this.notify();
return arrWT[index];
}
}
class Producer implements Runnable {
SyncStack ss = null;
public Producer(SyncStack ss) {
this.ss = ss;
}
public void run() {
for (int i = 0; i < 20; i++) {
WoTou wt = new WoTou(i);
ss.push(wt);
System.out.println("Producer: " + wt);
try {
Thread.sleep((int)Math.random()*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
SyncStack ss = null;
public Consumer(SyncStack ss) {
this.ss = ss;
}
@Override
public void run() {
for ( int i = 0; i < 20; i++ ) {
WoTou wt = ss.pop();
System.out.println("Consumer: " + wt);
try {
Thread.sleep((int)Math.random()*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
原文:http://www.cnblogs.com/myseries/p/7492631.html