java_Thread生产者与消费者 Demo

时间:2022-02-07 23:42:21
 package com.bjsxt.Thread.Demo;
public class ProducerConsumer {
/**
* 生产者与消费者
* @param args
*/
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();// 开启线程
}
} /**
* Woto类
*/
class WoTo {
int id;
WoTo(int id) {
this.id = id;
}
public String toString() {
return "WoTo : " + id;
}
} /**
* 框类(用来装馒头)
* @author wenfei
*/
class SyncStack {
int index = 0;
WoTo[] arrwt = new WoTo[6]; public synchronized void push(WoTo wt) { while (index == arrwt.length) { try {
this.wait();// 暂定当前对象 } catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();// 叫醒当前线程
arrwt[index] = wt;
index++;
} public synchronized WoTo pop() {
while (index == 0) { try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
index--;
return arrwt[index];
}
} /**
* 生产者
*
* @author wenfei
*/
class Producer implements Runnable {
SyncStack ss = null; Producer(SyncStack ss) {
this.ss = ss;
} @Override
public void run() {
// 生产wt
for (int i = 0; i <= 100; i++) {
WoTo wt = new WoTo(i);
ss.push(wt);// 往篮子里装窝头
System.out.println("生产了--->" + wt);
try {
// Thread.sleep(1000);//每生产一个睡眠一秒
Thread.sleep((int) Math.random() * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} } /**
* 消费者
*
* @author wenfei
*/
class Consumer implements Runnable {
SyncStack ss = null; Consumer(SyncStack ss) {
this.ss = ss;
} @Override
public void run() {
for (int i = 0; i <= 100; i++) {
WoTo wt = ss.pop();
System.out.println("消费了--->" + wt);
try {
// Thread.sleep(1000);//每消费一个睡眠一秒
Thread.sleep((int) Math.random() * 1000);//
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(wt);
}
} }