多个线程同时运行时,会产生线程并发可使用同步操作确保数据的安全性,如果需要各线程之间交互,可是使用线程等待和唤醒模式,在这里常用的等待唤醒中经典的模式为“生产者和消费者模式”
生产者和消费者由两类线程组成: 若干个生产者线程 负责提交用户的请求,若干个消费者线程负责处理生成出来的任务。 他们操作一块共享内存区进生成/消费的产品(数据): Mobile (手机编号)
生成者线程类: Provider : 无限制的生成手机
消费者线程类:Customer : 无限制的消费手机
共享存储区: Storage ( push 、pop) 存储手机的对象数组
测试类 行数据通信。```java
public class Mobile {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Mobile(int id) {
this.id = id;
}
}
存储区
```java
package com.j2008.provider_customer;
/**
* ClassName: Storage
* Description:
* date: 2020/11/10 15:32
* 存储区,它是生产者和消费者共享的空间 ( 生产者和消费者将该对象作为公有锁)
* @author wuyafeng
* @version 1.0 softeem.com
*/
public class Storage {
// 定义存储手机的对象数据
Mobile [] mobiles = new Mobile[10];
int index=0; // 个数
static int n=1000;
/**
* 存放手机
* @param mobile
*/
public synchronized void push(Mobile mobile){
//考虑容器上限已满,必须等待
while(index == mobiles.length){
System.out.println("容器已满,需等待");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//通知消费者取消费 ,将其他线程全部唤醒
this.notifyAll();
mobiles[index]=mobile;
index++;
}
/**
* 取出手机 1 2 3 4
* 1 2 3
* index--;
* mobile[index] =null
* @return 取出的手机对象
*/
public synchronized Mobile pop(){
Mobile m = null;
// 判断index是否小于0
while(index<=0){
//等待
System.out.println("容器中没有手机,需要等待");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
index--;
m = mobiles[index];
//将容器中的这个位置 设置为空
mobiles[index]=null;
// 通知生产者去生产
this.notifyAll();
return m;
}
public synchronized int getSize(){
return index;
}
}
生产者:
package com.j2008.provider_customer;
/**
* ClassName: Provider
* Description:
* date: 2020/11/10 15:54
*
* @author wuyafeng
* @version 1.0 softeem.com
*/
public class Provider implements Runnable {
//共享存储区
Storage storage =null;
public Provider(Storage storage){
this.storage = storage;
}
@Override
public void run() {
//手机编号
int n=1000;
//一直生产
while(true){
Mobile m = new Mobile(n);
storage.push(m);
System.out.println(Thread.currentThread().getName()+
"生产了一部手机,其编号:"+m.getId()+" 其库存:"+storage.getSize());
try {
Thread.sleep(1000);
} catch (InterruptedException