package com.huang.test.concurrent;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* Condition sigal 和 await 的数量要一样,或是一个signalAll 对应多个await
* await执行中:当前thread让出lock,阻塞。
* 返回(不管何种情况)后当前线程重新获取lock,继续执行
*/
public class ConditionSignalTest {
private ReentrantLock lock;
private Condition emptyCondition;
private int length = 10;
public ConditionSignalTest()
{
lock = new ReentrantLock(true);
emptyCondition = lock.newCondition();
}
class Productor extends Thread
{
@Override
public void run() {
super.run();
try {
lock.lock();
System.out.println("product start...");
//其他线程interrupt 导致本次重新获得锁
boolean isSuccess = emptyCondition.await(1000, TimeUnit.MILLISECONDS);
System.out.println("condition:" + isSuccess);
Thread.sleep(1000);
System.out.println("product end...");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("释放锁。。。");
lock.unlock();
}
}
}
private void test() {
ArrayList<Thread> producetors = new ArrayList<>();
for(int i = 0;i < length;i++)
{
producetors.add(new Productor());
}
for(int i = 0;i < length;i++)
{
producetors.get(i).start();
}
new Thread()
{
@Override
public void run() {
super.run();
try {
lock.lock();
Thread.sleep(100);
for(int i = 0;i < length;i++)
{
emptyCondition.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if(lock.isHeldByCurrentThread())
{
lock.unlock();
}
}
}
}.start();
}
public static void main(String[] args) {
ConditionSignalTest ct = new ConditionSignalTest();
ct.test();
}
}