消费者线程:
package cn.org.lin.cp;
public class Customer implements Runnable{
//仓库中
ShareData sd ;
public Customer(ShareData sd) {
this.sd = sd;
}
public ShareData getSd() {
return sd;
}
public void setSd(ShareData sd) {
this.sd = sd;
}
@Override
public void run() {
while(true){
sd.getData();
}
}
}
生产者线程:
package cn.org.lin.cp;
import java.util.Random;
//生产者
public class Producter implements Runnable {
ShareData sd ;
public Producter(ShareData sd) {
this.sd = sd;
}
public ShareData getSd() {
return sd;
}
public void setSd(ShareData sd) {
this.sd = sd;
}
@Override
public void run() {
String msg = "12345678o9asdfghjk";//假定生产者固有货物
while(true) {
char c =msg.charAt(newRandom().nextInt(msg.length()));
sd.putData(c);
}
}
}
仓库类:
package cn.org.lin.cp;
//仓库的数据
public class ShareData {
private char c;
boolean flag =false;//库存中有货物
//生产者线程执行此方法
public synchronized void putData(char c){
if(flag){
System.out.println("库中中有商品,不生产,等待");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.c = c ;
System.out.println("生产者生产了一个:"+c);
flag=true;
notify();
}
//消费者执行
public synchronized void getData(){
if(!flag){
System.out.println("库存中没有商品,等待生产");
try {
Thread.sleep(1000);
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("消费者消费了"+c);
flag=false;
notify();//通知其他等待的线程执行
}
}
测试类:
package cn.org.lin.cp;
public class TestDemo01 {
public static void main(String[] args) {
ShareData sd = new ShareData();
Producter p = new Producter(sd);
Customer c = new Customer(sd);
Thread sp = new Thread(p, "生产者");
Thread sc = new Thread(c, "消费者");
sp.start();
sc.start();
}
}