生产者代码
package com.cvicse.thread.product_consumer;
public class Producter extends Thread{
private ShareData shareData;
public Producter(ShareData shareData){
this.shareData = shareData;
}
@Override
public void run() {
for (char c = 'A'; c <= 'D'; c++) {
try {
Thread.sleep((long)(Math.random()*1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
shareData.putShareChar(c);
System.out.println(c + " is produced by Producer. ");
}
}
}
消费者代码
package com.cvicse.thread.product_consumer;
public class Consumer extends Thread{
private ShareData shareData;
public Consumer(ShareData shareData){
this.shareData = shareData;
}
@Override
public void run() {
char ch;
do{
try{
Thread.sleep((long)(Math.random()*1000));
}catch(InterruptedException e){
e.printStackTrace();
}
// 从仓库中取出产品
ch = shareData.getShareChar();
System.out.println(ch + " is consumed by Consumer. ");
}while (ch != 'D');
}
}
仓库代码
package com.cvicse.thread.product_consumer;
public class ShareData {
private char c;
private boolean signal = false;
public synchronized void putShareChar(char c){
while (signal) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.c = c;
this.signal = true;
notify();
}
public synchronized char getShareChar(){
while (!signal) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.signal = false;
notify();
return this.c;
}
}
测试类
package com.cvicse.thread.product_consumer;
public class MainTest {
public static void main(String[] args) {
ShareData shareData = new ShareData();
Thread producter = new Producter(shareData);
Thread consumer = new Consumer(shareData);
producter.start();
consumer.start();
}
}