41. waitnotify方法

it2022-05-06  3

wait()      等待,如果一个线程执行了wait方法,那么该线程就会进去一个以锁对象为标识符的线程池中等待

notity()    唤醒,如果一个线程执行了notity方法,那么就会唤醒以锁对象为标识符的线程池中等待线程的其中一个(至于唤醒哪一个,不能确定)

notifyAll()   唤醒所有的线程

wait notity使用注意事项:

      1.属于Object对象的

      2.必须要在同步代码块或者同步函数中使用

      3.必须要由锁对象调用

      4.要想唤醒等待的线程,它们的锁对象必须一样,否者无效

代码实例:

//生产者 消费者 商品,生产一个,就消费一个 //产品 class Product{ String name; double price; boolean flag = false;//判断是否生产完的标志 } //生产者 class Producer implements Runnable{ Product p; public Producer(Product p) { this.p = p; } @Override public void run() { int i = 0; while(true) { synchronized (p) { if(p.flag == false) { if(i%2 == 0) { p.name = "香蕉"; p.price = 2.0; }else { p.name = "苹果"; p.price = 6.5; } System.out.println("生产了"+p.name+"价格"+p.price); i++; p.flag = true;//生产完了 p.notify();//唤醒消费者消费 p.notifyAll(); }else { try { p.wait();//产品生产完了等待消费者去消费 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } } //消费者 class Customer implements Runnable{ Product p; public Customer(Product p) { this.p = p; } @Override public void run() { while(true) { synchronized (p) { if(p.flag == true) { System.out.println("消费者消费了"+p.name+"花费"+p.price); p.flag = false; p.notify();//唤醒生产者生产 }else { try { p.wait();//消费完了,等待生产者去生产 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } } public class Demo9 { public static void main(String[] args) { Product p = new Product(); Producer producer = new Producer(p); Customer customer = new Customer(p); Thread thread1 = new Thread(producer,"生产者"); Thread thread2 = new Thread(customer,"消费者"); thread1.start(); thread2.start(); } }

 

转载于:https://www.cnblogs.com/zjdbk/p/8971109.html


最新回复(0)