In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
In this issue, the editor will bring you about how to describe thread wait and notify through an example. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.
Scenario: in a class, one is the method to add elements to the container, the other is to return the container size, and now there are two threads, thread A calls the add method, thread B calls the return container size method, and when the size is 5, the B thread prompts and ends.
The code can be copied directly, running:
Public class UseWaitAndNotify {volatile List list = new ArrayList (); / / Why volatile is used here, please see: https://my.oschina.net/u/4049911/blog/3121294 public void add (Object o) {list.add (o);} public int size () {return list.size () } public void useWaitAndNotify () {new Thread (new Runnable () {@ Override public void run () {synchronized (this) {System.out.println ("size method start") / * it has to be not equal to 5, because it must not be equal to 5 at first, and then it will enter this method, execute the wait method, and the thread will wait at wait. * then cpu executes another method, and when the execution of another method equals 5, use notify to wake up waiting threads (threads waiting for the same lock). * then execute it down from the wait method to the end. * / if (list.size ()! = 5) {try {wait ();} catch (InterruptedException e) {/ / TODO Auto-generated catch block e.printStackTrace () }} System.out.println ("end of size method");}) .start (); synchronized (this) {System.out.println ("start of add method"); for (int iTuno switch I)
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.