Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use wait () and notify () mechanisms to complete sleep and kick

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about how to use wait () and notify () mechanisms to complete sleep and kicking. many people may not know much about it. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something from this article.

Use the wait () and notify () mechanisms to complete "sleep" and "kick". The actual consumer work is handled by the OnConsume (Object) method, as shown in listing 3:

Listing 3. Wake up and notify Consumer

/ * *

* Add an object to the Consumer.

* This is the entry point for the producer.

* After the item is added, the Consumer's thread

* will be notified.

*

* @ param the object to be'consumed 'by this consumer

, /

Public void add (Object o)

{

_ queue.add (o)

KickThread ()

}

/ * *

* Wake up the thread (without adding new stuff to consume)

*

, /

Public void kickThread ()

{

If (! this._thread.isInterrupted ()

{

Synchronized (_ waitForJobsMonitor)

{

_ waitForJobsMonitor.notify ()

}

}

}

Example: MessagesProcessor

To show you how the Consumer class works, we'll use a simple example. The MessagesProcessor class handles incoming messages asynchronously (that is, it does not interfere with the calling thread). Its job is to print each message when it arrives. MessagesProcessor has an internal Consumer that handles incoming message jobs. When a new job enters the empty queue, Consumer calls the processMessage (String) method to process it, as shown in listing 4:

Listing 4. MessagesProcessor class

Class MessagesProcessor

{

String _ name

/ / anonymous inner class that supplies the consumer

/ / capabilities for the MessagesProcessor

Private Consumer _ consumer = new Consumer ()

{

/ / that method is called on each event retrieved

Protected void onConsume (Object o)

{

If (! (o instanceof String))

{

System.out.println ("illegal use, ignoring")

Return

}

MessagesProcesser.this.processMessage ((String) o)

}

} .setName ("MessagesProcessor") .init ()

Public void gotMessageEvent (String s)

{

_ consumer.add (s)

}

Private void processMessage (String s)

{

System.out.println (_ name+ "processed message:" + s)

}

Private void terminate ()

{

_ consumer.terminateWait ()

_ name = null

}

MessagesProcessor ()

{

_ name = "Example Consumer"

}

}

As you can see from the code above, customizing Consumer is fairly simple. We use an anonymous inner class to inherit the Consumer class and overload the abstract method onConsume (). So, in our example, you only need to call processMessage.

Advanced features of the Consumer class

In addition to the basic requirements presented at the beginning, we also provide some advanced features for the Consumer class that we find useful.

Event notification

OnThreadTerminate (): this method is called only before the Consumer is terminated. We override this method for debugging purposes.

GoingToRest (): this method is called only before the Consumer thread goes into sleep (that is, only before _ waitForJobsMonitor.wait () is called). Such notification may be required only in complex situations where consumers are required to deal with a batch of processed work before going to sleep.

Termination

Terminate (): asynchronous termination of the Consumer thread.

TerminateWait (): sets the calling thread to wait until the consumer thread actually terminates.

In our example, if you use terminate () instead of terminateWait (), there will be a problem because the onConsume () method is called after setting _ name to a null value. This will cause the thread executing the processMessage to throw a NullPointerException.

Conclusion: benefits of the Consumer class

You can download the source code for the Consumer class in the Resources section. Please feel free to use the source code and extend it according to your needs. We found that using this class for multithreaded application development has many benefits:

Code reuse / elimination of duplicated code: if you have a Consumer class, you don't have to write a new consumer for each instance in your application. This can greatly save time if you frequently use producer-consumer solutions in application development. Also, keep in mind that repeating code is a fertile ground for errors. It also makes it more difficult to maintain the basic code.

Fewer errors: using validated code is a good practice to prevent errors, especially when dealing with multithreaded applications. Because the Consumer class has been debugged, it is more secure. Consumers also prevent thread-related errors by acting as a security intermediary between threads and resources. Consumers can access resources sequentially on behalf of other threads.

Beautiful, clear code: using the Consumer class helps us write simpler code that is easier to understand and maintain. If we don't use the Consumer class, we have to write code to handle two different functions: consumption logic (queue and thread management, synchronization, and so on) and code that specifies the consumer's usage or function.

After reading the above, do you have any further understanding of how to use the wait () and notify () mechanisms to complete sleep and kick? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report