读写锁 ReadWriteLock

读写锁 ReadWriteLock

package com.aop8.testJava;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;


/**
 * 读写锁 ReadWriteLock
 *
 */
public class TestReadWriteLock {

    public static void main(String[] args) {
        final ReadWriteLockDemo readWriteLockDemo=new ReadWriteLockDemo();

        //写锁
        new Thread(new Runnable() {
            public void run() {
                readWriteLockDemo.set((int)(Math.random()*1001));
            }
        },"Write").start();


        //多个读锁
        for (int i = 0; i < 100; i++) {
            new Thread(new Runnable() {

                public void run() {
                    readWriteLockDemo.get();
                }
            },"Read_"+i).start();;
        }
    }

}


class ReadWriteLockDemo {
    private int number=0;
    private ReadWriteLock lock=new ReentrantReadWriteLock();

    //读
    public void get(){
        lock.readLock().lock(); //上锁

        try{
            System.out.println(Thread.currentThread().getName()+" : "+number);
        }finally{
            lock.readLock().unlock(); //释放锁
        }
    }

    //写
    public void set(int number){
        lock.writeLock().lock();
        try{
            System.out.println(Thread.currentThread().getName()+" : "+number);
            this.number=number;
        }finally{
            lock.writeLock().unlock();
        }
    }

}

猜你喜欢

转载自blog.csdn.net/xiaojin21cen/article/details/81806231