温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java notify唤醒源代码的示例分析

发布时间:2021-11-20 18:03:52 来源:亿速云 阅读:136 作者:柒染 栏目:编程语言

这期内容当中小编将会给大家带来有关Java notify唤醒源代码的示例分析,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

Java notify唤醒在此对象监视器上等待的单个线程。相关的问题需要我们不断的学习,下面我们就看看如何才能更好的使用。如果所有线程都在此对象上等待,则会选择唤醒其中一个线程。

直到当前的线程放弃此对象上的锁定,才能继续执行被唤醒的线程。此方法只应由作为此对象监视器的所有者的线程来调用.

"当前的线程必须拥有此对象监视器"与"此方法只应由作为此对象监视器的所有者的线程来调用"说明wait方法与notify方法必须在同步块内执行,即synchronized(obj之内).

调用对像wait方法后,当前线程释放对像锁,进入等待状态.直到其他线程(也只能是其他线程)通过Java notify唤醒方法,或 notifyAll.该线程重新获得对像锁.
继续执行,记得线程必须重新获得对像锁才能继续执行.因为synchronized代码块内没有锁是寸步不能走的.看一个很经典的例子:

Java notify唤醒代码

package ProductAndConsume;   import java.util.List;   public class Consume implements Runnable{   private List container = null;   private int count;   public Consume(List lst){   this.container = lst;   }   public void run() {   while(true){   synchronized (container) {   if(container.size()== 0){   try {   container.wait();//放弃锁   } catch (InterruptedException e) {   e.printStackTrace();   }   }   try {   Thread.sleep(100);   } catch (InterruptedException e) {   // TODO Auto-generated catch block   e.printStackTrace();   }   container.remove(0);   container.notify();   System.out.println("我吃了"+(++count)+"个");   }   }   }   }   package ProductAndConsume;   import java.util.List;   public class Product implements Runnable {   private List container = null;   private int count;   public Product(List lst) {   this.container = lst;   }   public void run() {   while (true) {   synchronized (container) {   if (container.size() > MultiThread.MAX) {   try {   container.wait();   } catch (InterruptedException e) {   e.printStackTrace();   }   }   try {   Thread.sleep(100);   } catch (InterruptedException e) {   e.printStackTrace();   }   container.add(new Object());   container.notify();   System.out.println("我生产了"+(++count)+"个");   }   }   }   }   package ProductAndConsume;   import java.util.ArrayList;   import java.util.List;   public class MultiThread {   private List container = new ArrayList();   public final static int MAX = 5;   public static void main(String args[]){   MultiThread m = new MultiThread();   new Thread(new Consume(m.getContainer())).start();   new Thread(new Product(m.getContainer())).start();   new Thread(new Consume(m.getContainer())).start();   new Thread(new Product(m.getContainer())).start();   }   public List getContainer() {   return container;   }   public void setContainer(List container) {   this.container = container;   }

上述就是小编为大家分享的Java notify唤醒源代码的示例分析了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI