Java Thread Programming 1.8.3 - Inter-thread Commu

來源:互聯網
上載者:User
CubbyHole Example
The class CubbyHole (see Listing 8.9) simulates a cubbyhole. A cubbyhole is a slot that can have only one item in it at a time. One thread puts an item into the slot and another thread takes it out. If a thread tries to put an item into a cubbyhole that is already occupied, the thread blocks until the slot is available. If a thread tries to remove an item from an empty cubbyhole, the thread blocks until an item is added. In this example, the slot is a reference to an object. This technique allows objects to be handed off from one thread to another in a thread-safe manner.
CubbyHole是指一個通道,某一時刻只能容納一個東西,一個線程放,另一個線程取。如果已經有東西,不能再放,直到東西被取出。如果沒有東西,則不能取,直到放進去新東西。下面給出一個安全執行緒的解決方案:
CubbyHole.java
/*
 * Created on 2005-7-14
 *
 * Java Thread Programming - Paul Hyde
 * Copyright ? 1999 Sams Publishing
 * Jonathan Q. Bo 學習筆記
 *
 */
package org.tju.msnrl.jonathan.thread.chapter8;
/**
 * @author Jonathan Q. Bo from TJU MSNRL
 *
 * Email:jonathan.q.bo@gmail.com
 * Blog:blog.111cn.net/jonathan_q_bo
 *      blog.yesky.net/jonathanundersun
 *
 * Enjoy Life with Sun!
 *
 */
public class CubbyHole {
    private Object obj;
    public CubbyHole() {
        obj = null;
    }
  
    public synchronized void putIn(Object obj) throws InterruptedException{
        print("putIn() ... begin");
      
        while(this.obj != null){//等待,直到資料被取出
            print("putIn() wait ... begin");

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.