ReadWriteLock 读写锁测试

	static final ReadWriteLock lock = new ReentrantReadWriteLock(true);
	static Executor executor = Executors.newFixedThreadPool(4);
	public static void main(String[] args)  {
		//创建双读双写的线程
		executor.execute(new Read());
		executor.execute(new Read());
		executor.execute(new Write());
		executor.execute(new Write());

	}
	//读线程
	static class Read implements Runnable {
		public void run() {
			for (int i = 0; i < 1000; i++) {
				lock.readLock().lock();
				for (int j = 0; j < 10; j++) {
					ThreadUtil.sleep(1);
					System.out.println(Thread.currentThread().getName()+"read"+j);
				}
				lock.readLock().unlock();
			}
		}

	}
	//写线程
	static class Write implements Runnable {

		public void run() {
			for (int i = 0; i < 1000; i++) {
				lock.writeLock().lock();
				for (int j = 0; j < 10; j++) {
					ThreadUtil.sleep(1);
					System.out.println(Thread.currentThread().getName()+"write"+j);
				}
				lock.writeLock().unlock();
			}
		}

	}


截取执行结果片段

pool-1-thread-4write0
pool-1-thread-4write1
pool-1-thread-4write2
pool-1-thread-4write3
pool-1-thread-4write4
pool-1-thread-4write5
pool-1-thread-4write6
pool-1-thread-4write7
pool-1-thread-4write8
pool-1-thread-4write9
pool-1-thread-3write0
pool-1-thread-3write1
pool-1-thread-3write2
pool-1-thread-3write3
pool-1-thread-3write4
pool-1-thread-3write5
pool-1-thread-3write6
pool-1-thread-3write7
pool-1-thread-3write8
pool-1-thread-3write9
pool-1-thread-2read0
pool-1-thread-1read0
pool-1-thread-2read1
pool-1-thread-1read1
pool-1-thread-2read2
pool-1-thread-1read2
pool-1-thread-2read3
pool-1-thread-1read3
pool-1-thread-2read4
pool-1-thread-1read4
pool-1-thread-2read5
pool-1-thread-1read5
pool-1-thread-2read6
pool-1-thread-1read6
pool-1-thread-2read7
pool-1-thread-1read7
pool-1-thread-2read8
pool-1-thread-1read8
pool-1-thread-2read9
pool-1-thread-1read9

读锁时 别的线程可以读不可以写

写锁时 别的线程不可以读 不可以写



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值