In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-09-22 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.
The market share of Chrome browser on the desktop has exceeded 70%, and users are complaining about
The world's first 2nm mobile chip: Samsung Exynos 2600 is ready for mass production.According to a r
A US federal judge has ruled that Google can keep its Chrome browser, but it will be prohibited from
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
About us Contact us Product review car news thenatureplanet
More Form oMedia: AutoTimes. Bestcoffee. SL News. Jarebook. Coffee Hunters. Sundaily. Modezone. NNB. Coffee. Game News. FrontStreet. GGAMEN
© 2024 shulou.com SLNews company. All rights reserved.