java線程--ReentrantReadWriteLock讀寫鎖

讀寫鎖的使用個例

public class Test {
    static Lock lock = new ReentrantLock();

    static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    static Lock readLock = readWriteLock.readLock();

    static Lock writeLock = readWriteLock.writeLock();

    static int value = 0;

    static class ReadWriteLockDemo {

        public Object handleRead() {

            try {
                readLock.lock();
                Thread.sleep(1000);
                System.out.println(System.currentTimeMillis()+" read : "+value);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                readLock.unlock();
            }

            return value;
        }

        public void handleWrite(int val) {

            try {
                writeLock.lock();
                Thread.sleep(1000);
                value = val;
                System.out.println(System.currentTimeMillis()+" write : "+value);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                writeLock.unlock();
            }

        }

    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println(System.currentTimeMillis()+" : "+value);
        ReadWriteLockDemo demo = new ReadWriteLockDemo();
        Runnable r1 = new Runnable() {

            @Override
            public void run() {

                demo.handleRead();
            }
        };
        Runnable r2 = new Runnable() {
            
            @Override
            public void run() {
                demo.handleWrite(new Random().nextInt(100));

            }
        };

        for(int i=0;i<10;i++){
            new Thread(r2).start();
            new Thread(r1).start();
        }

    }

}
相關文章
相關標籤/搜索