多线程 | AQS锁 | 读写锁ReentrantReadWriteLock详解

/**
 * Created by zhangshukang on 2018/2/7.
 */
public class ReentrantReadWriteLockTest {

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

        String str = "hello";

        final ReadWriteLock lock = new ReentrantReadWriteLock();
        ExecutorService threadPool = Executors.newFixedThreadPool(10);

        ReadTask readTask = new ReadTask(lock.readLock());
        WriteTask writeTask = new WriteTask(lock.writeLock());

        threadPool.execute(() -> {
            readTask.read(8000,1,str);
        });

        Thread.sleep(500);

        threadPool.execute(()->{
            writeTask.write(10000,2,str);
        });

        Thread.sleep(500);

        threadPool.execute(() -> {
            readTask.read(8000,3,str);
        });
    }


    static class WriteTask {
        final Lock WRITE_LOCK;

        public WriteTask(Lock write_lock) {
            WRITE_LOCK = write_lock;
        }

        public void write(long time,int threadIndex,String str) {
            try {
                WRITE_LOCK.lock();
                System.out.println("线程"+threadIndex+"开始执行");
                Thread.sleep(time);
                str = "world";
                System.out.println(str);
            } catch (Exception e) {
            } finally {
                WRITE_LOCK.unlock();
                System.out.println("线程"+threadIndex+"结束执行"+System.getProperty("line.separator")+"---------------");
            }
        }
    }

    static class ReadTask {
        final Lock READ_LOCK;

        ReadTask(Lock read_lock) {
            this.READ_LOCK = read_lock;
        }

        public void read(long time,int threadIndex,String str) {
            try {
                READ_LOCK.lock();
                System.out.println("线程"+threadIndex+"开始执行");
                Thread.sleep(time);
                System.out.println(str);
            } catch (Exception e) {
            } finally {
                READ_LOCK.unlock();
                System.out.println("线程"+threadIndex+"结束执行"+System.getProperty("line.separator")+"---------------");
            }
        }
    }
}


运行结果:

线程1开始执行
hello
线程1结束执行
---------------
线程2开始执行
world
线程3开始执行
线程2结束执行
---------------
hello
线程3结束执行
---------------

猜你喜欢

转载自blog.csdn.net/woshilijiuyi/article/details/79289142