/**
* 线程并发协作/线程通信
* 多线程 并发协作模型“生产者/消费者模式”
* 模式分为三部分,生产者模块/ 线程 +缓冲区+消费者模块/线程
* 通过缓冲区将生产者与消费者之间的耦合解除,生产者产出数据交给缓冲区,消费者从缓冲区提取数据,这也解决了忙闲不均的问题
*/
public class TestThread3 {
}
class Data1{
//数据
private byte [] data;
public Data1(byte[] data) {
this.data = data;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
}
class Buffer1{
//缓冲区
public final Data1[] buff = new Data1[10];
//最大缓存10份数据
public int size;
//缓存中的数据量
public boolean isFulled(){
return size==10;
}
public synchronized void push(Data1 d){
//存数据,存取数据时synchronized(this)串行
while (isFulled()){
//当缓存已满时让生产者线程进入阻塞,通过循环使每次从阻塞变为就绪变为运行时重新判断缓存状况,直至不满结束循环存入数据
try {
this.wait();
//.wait()方法属于Object类,只能在synchronized语句块中使用,将当前对象锁释放并同时将当前线程变为阻塞状态,.wait()的阻塞需要.notify()唤醒
//this.wait()将this释放
} catch (Interrupted Exception e) {
throw new RuntimeException(e);
}
}
buff[size++]=d;
System.out.println(Thread.currentThread().getName()+” 存入第”+size+”个数据”);
this.notify();
//Object类的.notify(),唤醒一个this对象锁的阻塞线程
}
public boolean isEmpty(){
return size==0;
}
public Data1 pop(){
//取数据
Data1 d;
synchronized (this) {
while (isEmpty()) {
try {
this.wait();
//缓存为空的时候阻塞
//.wait(long ms)等待指定毫秒后自动唤醒
//.wait(long ms,int ns)等待多少毫秒多少微秒后自动唤醒
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println(Thread.currentThread().getName() + ” 取出第” + size + “个数据”);
d = buff[–size];
buff[size]=null;
this.notify();
//.notifyAll()唤醒同一对象锁上所有调用.wait()方法的线程,优先级高的线程先运行
}
return d;
}
}
class Maker1 extends Thread{
//生产者,没有生产产品之前,消费者要进入等待状态,而生产产品之后,又需要马上通知消费者消费
Buffer1 buff;
public Maker1(Buffer1 buff, String name) {
super(name);
this.buff = buff;
}
@Override
public void run() {
for (int i=0;i<10;i++){
buff.push(new Data1((“数据”+i).getBytes()));
}
}
}
class Consumer1 extends Thread{
//消费者,在消费之后,要通知生产者已经消费结束,需要继续生产新产品
Buffer1 buff;
public Consumer1(Buffer1 buff,String name) {
super(name);
this.buff = buff;
}
@Override
public void run() {
for (int i=0;i<20;i++){
buff.pop();
}
}
}
class Test3{
public static void main(String[] args) {
Buffer1 buff = new Buffer1();
new Maker1(buff,”生产者1″).start();
new Maker1(buff,”生产者2″).start();
new Consumer1(buff,”消费者1″).start();
}
}