生产者消费者线程

来源:互联网 发布:java速成教程 编辑:程序博客网 时间:2024/05/16 19:16

该简单生产者-消费者线程,属于本人学习过程中的一段练习代码.如有不足,请指点


package com.lanqiao.demo3;

/** 
* @author 大广子

* 类说明 :简单的生产者,消费者线程
*/ 
public class ThreadPTCS {
public static void main(String[] args) {
Cakes cakes = new Cakes("鸡蛋煎饼", 5);
Thread pt = new Thread(new Producter(cakes), "你大爷");
pt.start();
Thread cs = new Thread(new Consumer(cakes), "消费者");
cs.start();
//睡眠5秒后
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
// 退出
System.exit(0);
}


// 生产者线程
private static class Producter implements Runnable {
Cakes cakes = null;
int total=0;
public Producter(Cakes cakes) {
this.cakes = cakes;
}

@Override
public void run() {
while(true){
// TODO 自动生成的方法存根
synchronized (cakes) {

//如果true有饼 等着不生产
while(cakes.bool){
try {
cakes.wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
if(total%2==0){
cakes.setName("大煎饼");
cakes.setPrice(2);
}else{
cakes.setName("小煎饼");
cakes.setPrice(3);
}
System.out.println(Thread.currentThread().getName() + "生产了"
+ cakes.toString());
total++;
//有饼了,生产线程等待
cakes.setBool(true);
//有饼了 唤醒消费线程
cakes.notify();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}


// 消费者线程
private static class Consumer implements Runnable {
Cakes cakes = null;
public Consumer(Cakes cakes) {
this.cakes = cakes;
}


@Override
public void run() {
while(true){
synchronized (cakes) {
//如果没饼  等着
while(!cakes.bool){
try {
cakes.wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "吃了"
+ cakes.toString());
cakes.setBool(false);
//吃了之后 要唤醒生产线程
cakes.notify();
}
//睡一会,别跑太快了
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}

}

}

}



package com.lanqiao.demo3;
/*
 * 饼类
 * 
 */
public class Cakes {
String name;
double price;
boolean bool=false;
public Cakes(String name, double price) {
super();
this.name = name;
this.price = price;
}

public boolean isBool() {
return bool;
}


public void setBool(boolean bool) {
this.bool = bool;
}


public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return price+"元的"+name;
}

}


总结:控制好锁,采用线程控制wait() 让当前线程等待,notify()唤醒在此对象锁上等待的单个线程,用布尔值代表是否有产品,结合while(),实现先有产品后有消费的模式

0 0
原创粉丝点击