使用idea编辑生产者与消费者
生活随笔
收集整理的這篇文章主要介紹了
使用idea编辑生产者与消费者
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
public class Demo11 {public static void main(String[] args) {food f = new food();new cook(f).start();new waiter(f).start();}//靜態廚師類繼承Threadstatic class cook extends Thread{private food f;public cook(food f) {this.f = f;}@Overridepublic void run() {for(int i=0;i<100;i++){if(i%2==0){f.SetNameandTaste("餃子","牛肉圓蔥");}else{f.SetNameandTaste("包子","豬肉玉米");}}}}//靜態服務員類繼承Threadstatic class waiter extends Thread{private food f;public waiter(food f) {this.f = f;}@Overridepublic void run() {for(int i=0;i<100;i++) {try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}f.get();}}}//菜類static class food{private String name;private String taste;//true表示可以生產。boolean flag = true;public synchronized void SetNameandTaste(String name, String taste) {if (flag) {this.name = name;try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}this.taste = taste;flag = false; //把flag改成false 下一次調用flag時是false 為了進不來循環 避免廚師連續生產.this.notifyAll(); //喚醒當前在this下睡著的所有線程.try {this.wait(); //喚醒后讓廚師線程睡著.} catch (InterruptedException e) {e.printStackTrace();}}}public synchronized void get(){if(!flag) {System.out.println("服務員端走的是:" + name + "菜的味道是:" + taste);flag = true; //把flag改成true 下一次調用flag時是true 為了進不來循環 避免服務員連續端菜.this.notifyAll();//喚醒當前在this下睡著的所有線程.try {this.wait();//喚醒后讓服務員線程睡著.} catch (InterruptedException e) {e.printStackTrace();}}}}
}
總結
以上是生活随笔為你收集整理的使用idea编辑生产者与消费者的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【自建NAS】Ubuntu Server
- 下一篇: “野蛮人”姚振华是如何炼成的?