我在实际项目中写过的多线程
多线程中有分主线程和子线程,有用到对象队列ObjectQueue,首先看一下ObjectQueue这个类:
import java.util.ArrayList;
import java.util.NoSuchElementException;
/**
* Object Queue which support multi-thread consumer/supplier work
*/
public class ObjectQueue implements java.io.Serializable{
//private Logger logger;
private int maxLength;
private ArrayList queue;
private long waitTime;
private boolean inPreparing;
private boolean dying;// when queue is requested to die, this will set to true;
private String name;
/**
* @param maxLength Maximum length of the queue, if element size is equal to this one, we
* say queue is full. If no positive integer specified, will take as unlimited.
*/
public ObjectQueue(int maxLength){
this(maxLength, 0, "queue");
}
/**
* Wait time out in miliseconds
* @param maxLength
* @param wait time out in miliseconds, if 0, will wait until programically interrupted
* @param queueName name of the queue
*/
public ObjectQueue(int maxLength, long wait, String queueName){
this.maxLength= maxLength;
queue=new ArrayList();
inPreparing=false;
dying =false;
this.waitTime=wait;
name=queueName;
//logger= LoggerFactory.getLogger(this.getClass().getName()+"_"+queueName);
}
public String getName(){
return name;
}
public int getMaxLength(){
return maxLength;
}
/**
* Change max length of the queue.
* @param maxLength
*/
public void setMaxLength(int maxLength){
this.maxLength = maxLength;
}
/**
* How long will the supplier wait until there are space to store the object
* and the customer wait until there are objects to obtain
* @param time
*/
public void setWaitTime(long time){
this.waitTime=time;
}
/**
* @return size of current queue.
*/
public int size(){
return queue.size();
}
/**
* add a new object into queue, if queue is full, the operation will be
* locked until element been retrieved out
*/
public synchronized void addElement(Object obj){
while( !dying && isFull()){
try {
wait(waitTime);
} catch (InterruptedException e) { }
}
queue.add(obj);
notifyAll();
}
public synchronized boolean hasMoreElements(){
if( !dying && queue.size() > 0 ) return true;
while ( !dying && queue.size() == 0 && inPreparing ){
try {
log("wait to check hasMoreElements");
wait(waitTime);
log("check hasMoreElements: quesize="+queue.size()+", inpreparing="+inPreparing);
} catch (Interrupted