Java Inter-thread communication

Source: Internet
Author: User

Consider the classic queueing problem, where one thread is producing some data and the other is consuming it. To make the problem more interesting, assume that the producer has to wait until it will generate more data before the consumption is finished.

In a polling system, consumers waste a lot of CPU cycles, and it waits for producers to produce. Once the production is over, start polling, wasting more CPU cycles waiting for the consumer?? Complete, and so on. Obviously, this situation is not desirable.

To avoid polling, Java includes an elegant inter-process communication mechanism through the following methods:

    • Wait (): This method tells the calling thread to discard the monitor and go to sleep until another thread enters the same monitor and calls notify ().

    • notify (): This method wakes the first thread to call Wait () on the same object.

    • notifyall (): This method wakes all threads on the same object that call Wait (). The highest-priority thread will run first.

These methods are implemented as final methods in object, so all classes have them. These three methods can only be called from within a synchronized context.

These methods are declared in the object. Various forms of wait () exist so that you can specify a period of time to wait.

Example:

The following sample program includes four classes: Q, want to synchronize the queue, Producer, that is, the production queue of the entry thread object; Consumer, which consumes the queue's entry thread object and the Pc,tiny class, creates a Q, producer, and consumer.

The correct way to write this program in Java is to use the wait () and notify () methods to signal in two directions as follows:

Put: 1Got: 1Put: 2Got: 2Put: 3Got: 3Put: 4Got: 4Put: 5Got: 5         


Java Inter-thread communication

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.