多執行緒通訊(with;notify)
阿新 • • 發佈:2022-04-20
多執行緒通訊(with;notify)
-
在Java物件中,有兩種池
瑣池-----------------synchronized;
等待池-—--wait() ,notify() , notifyAll()
如果一個執行緒呼叫了某個物件的wait方法,那麼該執行緒進入到wait等待池中(並且已經將鎖釋放);如果未來的某一時刻,另外一個執行緒呼叫了相同物件的notify方法或者notifyAll方法,那麼該等待池中的執行緒;去執行wait後的方法
package com.Tread01; public class Product { private String proName; private String proType; //true為等待紅燈;false為綠燈;預設沒有商品,紅燈先進行生產;生產之後變成綠燈進行消費 boolean flag = true; public Product() { } public String getProName() { return proName; } public void setProName(String proName) { this.proName = proName; } public String getProType() { return proType; } public void setProType(String proType) { this.proType = proType; } public synchronized void setProduct(String Name,String Type){ if(!flag){//!true是指綠燈 try { //一開始預設是紅燈生產;當為!flag綠燈時;進行等待消費 wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.setProName(Name); this.setProType(Type); System.out.println("生產者生產了" + this.getProName() + "----" + this.getProType()); //生產完後變燈;開始消費 flag = false; //啟用消費執行緒中with後的程式碼塊 notify(); } //消費者和生產者公用一個產品屬性 public synchronized void getConsumer(){ if(flag){//flag是指紅燈 try { //當另一個執行緒執行完;釋放執行緒後,會回到wait處後繼續執行 wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("消費者消費了" + this.getProName() + "----" + this.getProType()); flag = true; notify(); } }
package com.Tread01; public class Consumer extends Thread{ private Product p; public Consumer(Product p){ this.p = p; } public void run() { for (int i = 1; i <=10; i++) { p.getConsumer(); } } }
package com.Tread01; public class Producer extends Thread { private Product p; public Producer(Product p) { this.p = p; } @Override public void run() { for (int nub = 1; nub <= 10; nub++) { if (nub % 2 == 0) { p.setProduct("哈爾濱", "啤酒"); } else { p.setProduct("菲律賓", "巧克力"); } } } }
package com.Tread01;
public class TestDemo001 {
public static void main(String[] args) {
Product p =new Product();
Producer producer =new Producer(p);
producer.start();
Consumer consumer = new Consumer(p);
consumer.start();
}
}