ReentrantLock与Condition

原创
2018/09/19 15:06
阅读数 95
package cunrent;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestCondition {
    public static void main(String[] args)  {
        final BoundedBuffer boundedBuffer = new BoundedBuffer();

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("t1 run");
                for (int i=0;i<100;i++) {
                    try {
                        Thread.sleep(10L);
                        boundedBuffer.put(Integer.valueOf(i));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }) ;

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("t2 run");
                for (int i=0;i<100;i++) {
                    try {
                        Thread.sleep(1000L);
                        Object val = boundedBuffer.take();
                        System.out.println(val);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }) ;

        t1.start();
        t2.start();
    }


}
class BoundedBuffer {
    final Lock lock = new ReentrantLock();
    final Condition notFull = lock.newCondition();
    final Condition notEmpty = lock.newCondition();

    final Object[] items = new Object[5];
    int putptr, takeptr, count;

    public void put(Object x) throws InterruptedException {
       System .out.println("put wait lock");
        lock.lock();//获得当前对象的锁
       System.out.println("put get lock");
        try {
            while (count == items.length) {
                System.out.println("buffer full, please wait");
                notFull.await();//阻塞当前线程,锁会被释放么
            }

            items[putptr] = x;
            if (++putptr == items.length)
                putptr = 0;
            ++count;
            notEmpty.signal();//唤醒其上的线程
        } finally {
            System.out.println("put un lock");
            lock.unlock();
        }
    }

    public Object take() throws InterruptedException {
        System.out.println("take wait lock");
        lock.lock();
        System.out.println("take get lock");
        try {
            while (count == 0) {
                System.out.println("no elements, please wait");
                notEmpty.await();//阻塞当前线程
            }
            Object x = items[takeptr];
            if (++takeptr == items.length)
                takeptr = 0;
            --count;
            notFull.signal();//唤醒其上的线程
            return x;
        } finally { System.out.println("take un lock");
            lock.unlock();
        }
    }
}

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部