這篇博客主要是通過模擬生活中的生產者消費者的案例,來進一步熟悉線程的相關操作。
/** * 生產者---廚師 */class PRoductor implements Runnable { private Food food; public Productor(Food food) { this.food = food; } @Override public void run() { for (int i = 0; i < 100; i++) { if (i % 2 == 0) { food.set("韭菜炒雞蛋","男人的好食品,多吃有益健康"); } else { food.set("蔥爆腰花","補腎氣,通膀胱,我好她也好"); } } }}/** * 消費者---服務員 */class Consumer implements Runnable{ private Food food; public Consumer(Food food) { this.food=food; } @Override public void run() { for (int i=0;i<100;i++){ food.get(); } }}/** * 產品---食物 */class Food{ private String name; private String content; //標記變量 private boolean flag=true; //true表示可以生產,false表示可以消費 public synchronized void set(String name,String concent) { if(!flag) { try { this.wait();//讓當前線程進入等待池等待,沒有指定時間, // 需要其它線程喚醒,釋放對象鎖,讓出CPU //sleep釋放CPU,不釋放對象鎖住 } catch (InterruptedException ex) { ex.printStackTrace(); } } this.setName(name); try { Thread.sleep(300); } catch (InterruptedException ex) { ex.printStackTrace(); } this.setContent(concent); flag=false;//表示可以消費 this.notify();//喚醒在該監視器上的一個線程 } //消費產品 public synchronized void get() { if(flag) { try { this.wait(); }catch (InterruptedException ex) { ex.printStackTrace(); } } try { Thread.sleep(300); }catch (InterruptedException ex) { ex.printStackTrace(); } System.out.println(this.getName()+":"+this.getContent()); flag=true; this.notify(); } public Food() { } public Food(String name, String content) { this.name = name; this.content = content; } public String getName() { return name; } public String getContent() { return content; } public void setName(String name) { this.name = name; } public void setContent(String content) { this.content = content; } @Override public String toString() { return "Food{" + "name='" + name + '/'' + ", content='" + content + '/'' + '}'; }}public class ThreadDemo { public static void main(String args[]) { Food food=new Food(); Productor productor=new Productor(food); Consumer consumer=new Consumer(food); new Thread(productor).start(); new Thread(consumer).start(); }}新聞熱點
疑難解答