189 8069 5689

Javanotify唤醒源代码的示例分析

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

湘西土家族网站制作公司哪家好,找成都创新互联公司!从网页设计、网站建设、微信开发、APP开发、响应式网站设计等网站项目制作,到程序开发,运营维护。成都创新互联公司成立于2013年到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选成都创新互联公司

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唤醒源代码的示例分析了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注创新互联行业资讯频道。


分享题目:Javanotify唤醒源代码的示例分析
URL地址:http://cdxtjz.cn/article/ppcgoc.html

其他资讯