管程法
- 生产者:负责生产的数据模块
- 消费者:负责处理数据的模块
- 缓冲区:消费者不能直接从生产者获取产品,生产者生产进入缓冲区
public class Demo {
public static void main(String[] args) {
container c = new container();
//生产者和消费者有一个共同点容器
new Thread(new producer(c)).start();
new Thread(new consumer(c)).start();
}
}
/**
* 生产者
*/
class producer implements Runnable{
container c ;
public producer(container c) {
this.c = c;
}
@Override
public void run() {
for(int i = 0;i < 100;i++){
c.product(new goods(i));
System.out.println(Thread.currentThread().getName() + "生产了第" + i + "件商品");
}
}
}
/**
* 消费者
*/
class consumer implements Runnable{
container c ;
public consumer(container c) {
this.c = c;
}
@Override
public void run() {
for(int i = 0;i < 100;i++){
System.out.println( Thread.currentThread().getName() + "消费了第" + c.consume().num + "件商品");
}
}
}
/**
* 商品
*/
class goods{
int num;
public goods(int num) {
this.num = num;
}
}
/**
* 缓冲区
*/
class container{
//能够储存商品的数量
goods[] buff = new goods[100];
//计数器
int count = 0;
/**
* 生产的同步方法
*/
public synchronized void product(goods good){
//生产者生产满了了就通知消费者消费
if(count == buff.length){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//生产者生产
buff[count++] = good;
notifyAll();
}
/**
* 消费的同步方法
*/
public synchronized goods consume(){
if(count == 0){
//消费者等待,通知生产者生产
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//消费
count--;
notifyAll();
return buff[count];
}
}
信号灯法
生产者消费者公用一个资源,两者之间相互依赖
- 生产者,没有生产产品之前,要通知消费者等待,生产了产品之后要通知消费者消费
- 消费者,消费之后要通知生产者已结束消费,需要生产产品
- 设置标志来显示信号
public class signal {
public static void main(String[] args) {
goods g = new goods("哇哈哈矿泉水");
new Thread(new producer(g)).start();
new Thread(new consumer(g)).start();
}
}
class producer implements Runnable {
goods g ;
public producer(goods g) {
this.g = g;
}
@Override
public void run() {
while (true)
g.product();
}
}
class consumer implements Runnable{
goods g;
public consumer(goods g) {
this.g = g;
}
@Override
public void run() {
while (true)
g.consume();
}
}
class goods{
String name;
public goods(String name) {
this.name = name;
}
boolean flag = true;
public synchronized void product(){
if(!flag){//通知消费者消费,生产者等待
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "生产了" + name);
flag = !flag;
notifyAll();
}
public synchronized void consume(){
if(flag){//消费者等待,生产者生产
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
flag = !flag;
System.out.println(Thread.currentThread().getName() + "消费了" + name);
notifyAll();
}
}