java線程--Condition

Conditon 使用方法

public class Test {

    public static ReentrantLock lock = new ReentrantLock(true);
    public static Condition condition = lock.newCondition();
    static class Reenter implements Runnable {

        @Override
        public void run() {


            try {
                lock.lock();
                condition.await();
                System.out.println("thread is going on");
            } catch (InterruptedException e) {

                e.printStackTrace();
            } finally{
                lock.unlock();
            }
        }


    }

    public static void main(String[] args) throws InterruptedException {

        Reenter reentrant = new Reenter();
        Thread t1 = new Thread(reentrant,"t1");
        t1.start();
        Thread.sleep(1000);
        lock.lock();
        condition.signal();
        lock.unlock();
    }

}

jdk內部使用案例

ArrayBlockingQueue 爲例(選取部分代碼)

public class ArrayBlockingQueue<E> extends AbstractQueue<E>
        implements BlockingQueue<E>, java.io.Serializable {
    final Object[] items;
    final ReentrantLock lock;

    /** Condition for waiting takes */
    private final Condition notEmpty;

    /** Condition for waiting puts */
    private final Condition notFull;

    public ArrayBlockingQueue(int capacity, boolean fair) {
        if (capacity <= 0)
            throw new IllegalArgumentException();
        this.items = new Object[capacity];
        lock = new ReentrantLock(fair);
        notEmpty = lock.newCondition();
        notFull =  lock.newCondition();
    }

    public void put(E e) throws InterruptedException {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == items.length)
                notFull.await();
            enqueue(e);
        } finally {
            lock.unlock();
        }
    }

    private void enqueue(E x) {
        // assert lock.getHoldCount() == 1;
        // assert items[putIndex] == null;
        final Object[] items = this.items;
        items[putIndex] = x;
        if (++putIndex == items.length)
            putIndex = 0;
        count++;
        notEmpty.signal();
    }
}
相關文章
相關標籤/搜索