package test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* 安全隊列
* @author hlw
* @param <T>
*
*/
public class QueueTest<T> {
List<T> tasks;
ReentrantLock locker;
Condition hasJob;
AtomicInteger jobs = new AtomicInteger(0);
public QueueTest(){
tasks = new ArrayList<T>();
locker = new ReentrantLock();
hasJob = locker.newCondition();
}
/**
* 把任務放到隊列
* @param job
*/
public void putJob(T job){
locker.lock();
try {
tasks.add(job);
hasJob.signal();
} finally{
locker.unlock();
}
}
/**
* 從隊列裏取任務
* @return
* @throws InterruptedException
*/
public T tackJob() throws InterruptedException{
locker.lock();
try {
if (tasks.size()<0) {
System.out.println(Thread.currentThread().getId() + "==>waiting");
hasJob.wait();
}
} finally{
locker.unlock();
}
return tasks.remove(0);
}
}
java