多线程开发中经典的案例。生产者、消费者案例
- 若在Food类中,不添加get,set方法,那么没个菜品不会和它的功能对应上。
- 程序一开始,线程将会开始抢占资源
package com.xiaofeng.example;
/**
* 生产者、消费者案例
* @author XiaoFeng1015
*/
public class TheadDemo5 {
public static void main(String[] args) {
Food food = new Food();
Producter p = new Producter(food);
Customers c = new Customers(food);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
class Producter implements Runnable {
private Food food;
public Producter(Food food) {
this.food = food;
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
if (i % 2 == 0) {
// food.setName("银耳莲子汤!");
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// food.setEfficasy("功效:美容养颜!");
food.set("银耳莲子汤!", "功效:美容养颜!");
} else {
// food.setName("糖醋里脊!");
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// food.setEfficasy("功效: 酸甜可口!");
food.set("糖醋里脊!", "功效: 酸甜可口!");
}
}
}
}
class Customers implements Runnable {
private Food food;
public Customers(Food food) {
this.food = food;
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// System.out.println(food.getEfficasy() + "-->" + food.getName());
food.get();
}
}
}
// 使用同步方法将生产和消费包裹起来。
class Food {
private String name;
private String efficasy;
public Food() {
super();
}
public Food(String name, String efficasy) {
super();
this.name = name;
this.efficasy = efficasy;
}
public synchronized void set(String name, String efficasy) {
this.setName(name);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.setEfficasy(efficasy);
}
public synchronized void get() {
// 加休眠的目的:为了防止get在一开始时取空
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(this.getName() + "-->" + this.getEfficasy());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEfficasy() {
return efficasy;
}
public void setEfficasy(String efficasy) {
this.efficasy = efficasy;
}
}
结果:
两种菜品会在一段时间内只显示一个,因为在访问一个同步方法时,另一个同步方法不允许被访问。