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 refers to a channel, which can accommodate only one thing at a time, one thread is put, and the other thread is retrieved. If something already exists, it cannot be placed until it is taken out. If there is nothing, you cannot take it until it is put into the new thing. The following is a thread-safe solution:
CubbyHole. java
/*
* Created on 2005-7-14
*
* Java Thread Programming-Paul Hyde
* Copyright? 1999 Sams Publishing
* Jonathan Q. Bo study notes
*
*/
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) {// wait until the data is retrieved
Print ("putIn () wait... begin ");
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