package com.Thread;
public class Custom_Producer {
public static void main(String[] args) {
//共享资源
Production pro = new Production();
Custom custom = new Custom(pro);
Producer producer = new Producer(pro);
new Thread(producer).start();
new Thread(custom).start();
}
}
//资源
class Production {
private String src ;
/**
* 信号
* flag ---> true 生产,消费等待, 生产完成,通知消费
* flag ---> false 消费,生产等待, 消费完成,通知生产
*/
private boolean flag = true;
public synchronized void product(String src) throws Exception{
if(!flag ) {// false 生产等待
this.wait();
}
//开始生产
Thread. sleep(500);
//生产完毕
this.src = src;
System. out.println("生产了----------->" + src);
//通知消费
this.notify();
//停止生产
this.flag = false;
}
public synchronized void custom() throws Exception {
if(flag ) {// true 消费等待
this.wait();
}
//开始消费
System. out.println("消费了---" +src );
//消费完毕
//通知生产
this.notifyAll();
//停止消费
this.flag = true;
}
}
//生产
class Producer implements Runnable {
Production p ;
public Producer(Production p) {
this.p = p;
}
@Override
public void run() {
for(int i=0; i<20; i++) {
if(0==i%2) {
try {
p.product( "奇数====生产了" + i +" 个");
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
p.product( "偶数====生产了" + i +" 个");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
//消费
class Custom implements Runnable {
Production p ;
public Custom(Production p) {
this.p = p;
}
@Override
public void run() {
for(int i=0; i<20; i++) {
try {
p.custom();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}