Java Thread Programming 1.8.1 - Inter-thread Commu

來源:互聯網
上載者:User
The Need for Inter-thread Signaling
Through synchronization, one thread can safely change values that another thread will read. How does the second thread know that the values have changed? What if the second thread is waiting for the values to change by rereading the values every few seconds?
One not-so-good way that a thread can wait for a value to change is by using a busy/wait:
while ( getValue() != desiredValue ) {
Thread.sleep(500);
}
Such code is called a busy/wait because the thread is busy using up processor resources to continually check to see if the value has changed. To use fewer resources, the sleep time could be increased, but then the thread might not find out about the change for quite some time. On the other hand, if the sleep time is reduced, the thread will find out sooner, but will waste even more of the processor resources. In Java, there is a much better way to handle this kind of situation: the wait/notify mechanism.
有時候我們需要線程間的通訊,比如第二個線程如何知道第一個線程的某些值發生了改變?不太好的方法如上,稱之為busy/wait,通過不斷迴圈並結合Thread.sleep()測試值是否發生變化,會佔用處理器資源,並且迴圈的頻率不容易掌握,快了浪費資源,慢了降低反應速度。像這種情況,java中給出了一種更好的解決方案:wait/notify機制
The Wait/Notify Mechanism
The wait/notify mechanism allows one thread to wait for a notification from another thread that it may proceed.
Minimal Wait/Notify
At a bare minimum, you need an object to lock on and two threads to implement the wait/notify mechanism.
Imagine that there is a member variable, valueLock, that will be used for synchronization:
private Object valueLock = new Object();
The first thread comes along and executes this code fragment:
synchronized ( valueLock ) {
try {
        valueLock.wait();
} catch ( InterruptedException x ) {
        System.out.println(“interrupted while waiting”);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.