薪火华扬
www.hyserver.com
微信moonli39
package com.salmon.test4;
/**
* 用来描述 共享资源类 窝头
* @author salmon
*
*/
public class WoTou {
// 每一个窝头的编号
String num;
// 创建一个 窝头的时候 就给一个编号
public WoTou(String num){
this.num = num;
}
}
package com.salmon.test4;
/**
* 消费者 线程类
*
* @author salmon
*
*/
public class Consume implements Runnable {
// 共享资源 筐子
private SyncStack ss;
//
public Consume(SyncStack ss) {
this.ss = ss;
}
@Override
public void run() {
for (int i = 1; i <=10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//
WoTou w = ss.pop();
System.out.println(Thread.currentThread().getName()+"---"+w.num);
}
}
}
package com.salmon.test4;
/**
* 生产者 线程类
* @author salmon
*
*/
public class Producer implements Runnable {
// 共享资源 筐子
private SyncStack ss;
//
public Producer(SyncStack ss){
this.ss = ss;
}
@Override
public void run() {
// 每个生产者 能够生产 30 个窝头
for (int i = 1; i <= 30; i++) {
WoTou w = new WoTou(Thread.currentThread().getName()+"---"+i+"****"+ss.number++);
ss.push(w);
System.out.println(Thread.currentThread().getName()+"---"+w.num);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.salmon.test4;
/**
* 共享资源 放窝头的筐子
* @author salmon
*
*/
public class SyncStack {
// 总计数器
static int number = 1;
// 计数器
private int index = 0;
// 筐子
private WoTou ws[] = new WoTou[20];
// 给筐子中放窝头
public synchronized void push(WoTou w){
// 判断筐子是不是满了
while(index==ws.length){
try {
// 就让当前线程等待
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 唤醒这个筐子对象上等待线程(单个线程)
this.notify();
// 生产值就放一个窝头 到筐子中
ws[index] = w;
index++;
}
// 给消费这 提供的 从筐子中 拿走窝头的方法
public synchronized WoTou pop(){
while(index ==0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//
this.notify();
// 从筐子中取得一个窝头
index--;
WoTou w = ws[index];
return w;
}
}
package com.salmon.test4;
public class Test {
public static void main(String[] args) {
// 准备一个 共享资源 筐子
SyncStack ss = new SyncStack();
// 创建两个生产者
Producer p1 = new Producer(ss);
Producer p2 = new Producer(ss);
Thread tp1 = new Thread(p1,"zhangsan");
Thread tp2 = new Thread(p2,"wangwu");
tp1.start();
tp2.start();
// 创建 三个消费
Consume c1 = new Consume(ss);
Consume c2 = new Consume(ss);
Consume c3 = new Consume(ss);
Thread tc1 = new Thread(c1,"xiaoming");
Thread tc2 = new Thread(c2,"xiaoyi");
Thread tc3 = new Thread(c3,"laorui");
tc1.start();
tc2.start();
tc3.start();
}
}