AQS之ReadWriteLock

AQS之ReadWriteLock_第1张图片
读写锁

高16位表示读锁,低16位表示写锁


AQS之ReadWriteLock_第2张图片
ReadLock.png

ReadLock和WriteLock都继承自

代码示例

public class ThreadPoolDemo {
    public  static class Task implements Runnable{
        ReadWriteLock lock;

        public Task(ReadWriteLock lock) {
            this.lock = lock;
        }
        @Override
        public void run() {
            Lock writeLock=lock.writeLock();
            try{
                writeLock.lock();
                System.out.println("start ! Thread name:"+Thread.currentThread().getName());
                Thread.sleep(100);
            }catch (Exception ex){

            }finally {
                System.out.println("end ! Thread name:"+Thread.currentThread().getName());
                writeLock.unlock();
            }

        }
    }
    public static void main(String[] args) {
        ExecutorService executorService= Executors.newFixedThreadPool(10);
        ReadWriteLock readWriteLock=new ReentrantReadWriteLock();
        for (int i=0;i<10;i++){
            executorService.submit(new Task(readWriteLock));
        }
    }
}
写锁,一个线程拿到锁,sleep 100ms后释放锁,其他线程才能拿到锁
start ! Thread name:pool-1-thread-1
end ! Thread name:pool-1-thread-1
start ! Thread name:pool-1-thread-2
end ! Thread name:pool-1-thread-2
start ! Thread name:pool-1-thread-3
end ! Thread name:pool-1-thread-3
start ! Thread name:pool-1-thread-4
end ! Thread name:pool-1-thread-4
start ! Thread name:pool-1-thread-5
end ! Thread name:pool-1-thread-5
start ! Thread name:pool-1-thread-6
end ! Thread name:pool-1-thread-6
start ! Thread name:pool-1-thread-7
end ! Thread name:pool-1-thread-7
start ! Thread name:pool-1-thread-8
end ! Thread name:pool-1-thread-8
start ! Thread name:pool-1-thread-9
end ! Thread name:pool-1-thread-9
start ! Thread name:pool-1-thread-10
end ! Thread name:pool-1-thread-10

你可能感兴趣的:(AQS之ReadWriteLock)