Java Thread Programming 1.8.3 - Inter-thread …

2008-02-23 09:35:08来源:互联网 阅读 ()

新老客户大回馈,云服务器低至5折

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.csdn.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");
wait();
print("putIn() wait ... end");
}
this.obj = obj;//添加新对象
notifyAll();//通知其它线程:有对象可取
print("putIn() ... end");
}
public synchronized Object takeOut()throws InterruptedException{
print("takeOut() ... begin");
while(obj == null){//等待,直到有数据可以取
print("takeOut() wait ... begin");
wait();
print("takeOut() wait ... end");
}
Object temp = obj;
obj = null;//将原数据清空
notifyAll();//通知其它线程:数据已取出,可填新数据
print("takeOut() ... end");
return temp;
}
public void print(String msg){
String temp = Thread.currentThread().getName();
System.out.println(temp " - " msg);
}
}
CubbyHoleMain.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.csdn.net/jonathan_q_bo
* blog.yesky.net/jonathanundersun
*
* Enjoy Life with Sun!
*
*/
public class CubbyHoleMain {
public static void print(String msg){
String temp = Thread.currentThread().getName();
System.out.println(temp " - " msg);
}
public static void main(String[] args) {
final CubbyHole ch = new CubbyHole();
Runnable runA = new Runnable(){
public void run(){
try{
Thread.sleep(500);//故意晚一些执行,让其它线程先取数据
String str;
str="multithreads";
ch.putIn(str);//可一直存
print("run() putIn() " str);
str = "programming";
ch.putIn(str);
print("run() putIn() " str);

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Struts原理与实践 - -

下一篇:jspSmartUpload上传下载全攻略 (一、安装篇 )