今天我们将通过线程来谈一谈生产者消费者的问题
首先我们写一个小程序生产一个商品并消费一个商品
/**
* 写一个商品者生产消费者消费的线程小程序
* @author lover
*
*/
class goods{
private int sum=1;
private String name;
public void set(String name){
this.name=name+sum;
sum++;
System.out.println(sum);
System.out.println("....生产...."+this.name);
}
public void out(){
System.out.println(".......消费........"+this.name);
}
}
class produce implements Runnable{
goods s;
public produce(goods s){
this.s=s;
}
public void run(){
while(true){
s.set("面包");
}
}
}
class customer implements Runnable{
goods s;
public customer(goods s){
this.s=s;
}
public void run(){
while(true){
s.out();
}
}
}
public class ShangPin {
public static void main(String[] args) {
goods s=new goods();
produce t1=new produce(s);
customer t2=new customer(s);
Thread t11=new Thread(t1);
Thread t22=new Thread(t2);
t11.start();
t22.start();
}
}
运行结果如下
....生产....面包19312
19314
....生产....面包19313
19315
....生产....面包19314
19316
....生产....面包19315
19317
....生产....面包19316
19318
....生产....面包19317
19319
....生产....面包19318
19320
.......消费........面包19166
.......消费........面包19319
.......消费........面包19319
.......消费........面包19319
运行之后发现一个很严重的问题出现了多生产和消费已经消费的产品,此时我们希望的是能够生产一个消费一个。之后我们改进代码
/**
* 写一个商品者生产消费者消费的线程小程序
* @author lover
*
*/
class goods{
private int sum=1;
private String name;
boolean flag=false;
public synchronized void set(String name){
if(!flag){
this.name=name+sum;
sum++;
System.out.println("....生产...."+this.name);
flag=true;
notifyAll();
}else{
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public synchronized void out(){
if(flag){
System.out.println(".......消费........"+this.name);
flag=false;
notifyAll();
}else{
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class produce implements Runnable{
goods s;
public produce(goods s){
this.s=s;
}
public void run(){
while(true){
s.set("面包");
}
}
}
class customer implements Runnable{
goods s;
public customer(goods s){
this.s=s;
}
public void run(){
while(true){
s.out();
}
}
}
public class ShangPin {
public static void main(String[] args) {
goods s=new goods();
produce t1=new produce(s);
customer t2=new customer(s);
Thread t11=new Thread(t1);
Thread t22=new Thread(t2);
t11.start();
t22.start();
}
}
我们来看一下结果
`....生产....面包45863
.......消费........面包45863
....生产....面包45864
.......消费........面包45864
....生产....面包45865
.......消费........面包45865
....生产....面包45866
.......消费........面包45866
....生产....面包45867
.......消费........面包45867
....生产....面包45868
.......消费........面包45868
....生产....面包45869
.......消费........面包45869
....生产....面包45870
.......消费........面包45870
....生产....面包45871
`
已经很好的解决了出现的问题
下一节我们将使用jdk1.5的方法来完善这个小程序