生产者和消费者的简单案例
1.两个线程共享一个对象的资源;
2.生产者生产时,消费者需要等待,生产完了以后唤醒消费者,让生产者进入等待状态;
消费者使用数据时,生产者要等待,消费者使用完了数据以后,唤醒生产者;
3.使用一个标识符来进行控制两个线程的状态
==============================================================================================================================
共享的类
package com.telneting.sychronized.productorandcustomer;
/**
* 生产者和消费者共同使用的类数据
* @author Andy
*
*/
public class Dishes {
private String name = null;
//标识符号,控制线程是否等待
private boolean flag = true;
/**
* 生产食物的方法,让生产者进行调用
* @param food
*/
public synchronized void cook(String food){
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.name = food;
System.out.println("师傅正在做"+name);
//让生产者等待
this.flag = false;
//唤醒消费者
this.notify();
}
/**
* 消费食物的类,让消费者进行调用
*/
public synchronized void eat(){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(name != null){
System.out.println("顾客正在吃"+name);
}
//唤醒生产者
this.notify();
//让消费者等待
this.flag = true;
}
}
生产者类
package com.telneting.sychronized.productorandcustomer;
public class Cook implements Runnable{
private Dishes dishes;
public Cook(){}
public Cook(Dishes dishes){
this.dishes = dishes;
}
@Override
public void run() {
for(int i=0; i<20; i++){
if(i%2 == 0){
dishes.cook("鱼香肉丝");
}else{
dishes.cook("麻辣鸡丝");
}
}
}
}
package com.telneting.sychronized.productorandcustomer;
public class Customer implements Runnable{
private Dishes dishes;
public Customer(Dishes dishes) {
this.dishes = dishes;
}
@Override
public void run() {
for(int i=0; i<20; i++){
dishes.eat();
}
}
}
测试类
package com.telneting.sychronized.productorandcustomer;
public class Test {
public static void main(String[] args) {
Dishes dishes = new Dishes();
Cook cook = new Cook(dishes);
Customer customer = new Customer(dishes);
new Thread(cook).start();
new Thread(customer).start();
}
}
显示的结果
..........