线程通信问题
用 notifyall 和 wait 和锁 的方法 解决多线程并发数据错乱问题
模拟厨师做菜和服务员端菜情况:
public class rr {
public static void main(String[] args) {
Food food=new Food();
new Cook(food).start();
new Waiter(food).start();
}
}
class Food{
private String name;
private String taste;
private boolean flag=true;
public synchronized void set(String name,String taste){
if(flag) {
this.name = name;
this.taste = taste;
System.out.println("1厨师做好了菜;菜名:" + this.name + "味道:" + this.taste);
flag=false;
}
this.notifyAll();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void get() {
if(!flag) {
System.out.println("2端出做好的菜;菜名:" + this.name + "味道:" + this.taste);
flag=true;
}
this.notifyAll();
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Cook extends Thread{
Food food;
Cook(Food food){
this.food=food;
}
public void cook(){
for(int i=0;i<50;i++){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(i%2==0){
food.set("酸菜鱼","酸味");
}else {
food.set("糖醋排骨","甜味");
}
}
}
@Override
public void run() {
cook();
}
}
class Waiter extends Thread{
Food food;
Waiter(Food food){
this.food=food;
}
public void take(){
for(int i=0;i<50;i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
food.get();
}
}
@Override
public void run() {
take();
}
}