consumed.await(); //放弃lock进入睡眠
}
/*生产苹果*/
System.out.println("Apple produced.");
available = true;
produced.signal(); //发信号唤醒等待这个Condition的线程
} finally {
lock.unlock();
}
}
public void consume() throws InterruptedException {
lock.lock();
try {
if(!available){
produced.await();//放弃lock进入睡眠
}
/*吃苹果*/
System.out.println("Apple consumed.");
available = false;
consumed.signal();//发信号唤醒等待这个Condition的线程
} finally {
lock.unlock();
}
}
}
ConditionTester:
public class ConditionTester {
public static void main(String[] args) throws InterruptedException{
final Basket basket = new Basket();
//定义一个producer
Runnable producer = new Runnable() {
public void run() {
try {
basket.produce();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
};
//定义一个consumer
Runnable consumer = new Runnable() {
public void run() {
try {
basket.consume();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
};
ExecutorService service = Executors.newCachedThreadPool();
for(int i=0; i < 10; i++)
service.submit(consumer);
Thread.sleep(2000);
for(int i=0; i<10; i++)
service.submit(producer);
service.shutdown();
}
}
5: Synchronizer:同步装置
Java 5.0里新加了4个协调线程间进程的同步装置,它们分别是Semaphore, CountDownLatch, CyclicBarrier和Exchanger.
Semaphore:
用来管理一个资源池的工具,Semaphore可以看成是个通行证,线程要想从资源池拿到资源必须先拿到通行证,Semaphore提供的通行证数量和资源池的大小一致。如果线程暂时拿不到通行证,线程就会被阻断进入等待状态。以下是一个例子:
public class Pool {
ArrayList
Semaphore pass = null;
public Pool(int size){
//初始化资源池
pool = new ArrayList
for(int i=0; i
}
//Semaphore的大小和资源池的大小一致
pass = new Semaphore(size);
}
public String get() throws InterruptedException{
//获取通行证,只有得到通行证后才能得到资源
pass.acquire();
return getResource();
}
public void put(String resource){
//归还通行证,并归还资源
pass.release();
releaseResource(resource);
}
private synchronized String getResource() {
String result = pool.get(0);
pool.remove(0);
System.out.println("Give out "+result);
return result;
}
private synchronized void releaseResource(String resource) {
System.out.println("return "+resource);
pool.add(resource);
}
}
SemaphoreTest:
public class SemaphoreTest {
public static void main(String[] args){
fin