package houy.qing.demo;
public class ProducerSummer {
public static void main(String[] args) {
SyncStack ss = new SyncStack();
new Thread(new Producer(ss)).start();
new Thread(new Consumer(ss)).start();
}
}
class WoTo{
int id;
public WoTo(int id){
this.id = id;
}
public String toString() {
return "woto :" + id;
}
}
class SyncStack{
int index = 0;
WoTo[] arrWoTo = new WoTo[6];
public synchronized void push(WoTo wt){
while (index == arrWoTo.length) {
try {
System.out.println("系统当前时间:" + System.currentTimeMillis());
this.wait(5*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("系统当前时间:" + System.currentTimeMillis());
this.notify();
arrWoTo[index] = wt;
System.out.println("生产:"+ wt);
index++;
}
public synchronized WoTo pop(){
while (index == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
index--;
return arrWoTo[index];
}
}
class Producer implements Runnable{
SyncStack ss = null;
public Producer(SyncStack ss) {
this.ss = ss;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
WoTo wt = new WoTo(i);
ss.push(wt);
try {
Thread.sleep((int)Math.random()*200);
} 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++) {
WoTo wtTo = ss.pop();
System.out.println("消费:" + wtTo);
try {
Thread.sleep((int)Math.random()*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Java并发:生产者与消费者经典问题(马士兵)
最新推荐文章于 2025-05-29 16:11:54 发布