您的位置:首页 > 其它

对于多线程之间的通讯的理解

2016-12-01 20:03 435 查看
老规矩,直接贴代码

package packageExercise;

public class Demo1 {
public static void main(String[] args) {
Niuroumian product = new Niuroumian();
Mianguan producer = new Mianguan(product);
Shike customer = new Shike(product);
producer.start();
customer.start();
}
}

//牛肉面类
class Niuroumian{
String name;//名字
int price;//价格
int flag = 0;
}
//面馆类
class Mianguan extends Thread{
Niuroumian product;//牛肉面
int i = 0;
public Mianguan(Niuroumian product) {
this.product = product;
}
public void run() {
while(true){
synchronized (product) {
if(product.flag == 0){
if(i % 2 == 0){
product.name = "大碗牛肉面";
try {
sleep(1);//此处让面馆线程睡1毫秒,增大线程出现安全问题的概率,
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
product.price = 10;
}else{
product.name = "小碗牛肉面";
product.price = 5;
}
i++;
System.out.println("面馆拉好了" + product.name + product.price);
product.flag = 1;
product.notify();
}else{
try {
product.wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}
}
}
//食客类
class Shike extends Thread{
Niuroumian product;
public Shike(Niuroumian product) {
this.product = product;
}

public void run() {
while(true){
synchronized (product) {
if (product.flag == 1) {
System.out.println("食客吃完了" + product.name + product.price);
product.flag = 0;
product.notify();

}
else{
product.notify();
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: