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");