好记性不如铅笔头

java, think_in_java, 编程

《Java编程思想》读书笔记:ReentrantReadWriteLock

最近在整理 Java 的多线程相关的技术,这里备份下关于【 ReentrantLock 】代码。

github:

https://github.com/cstriker1407/think_in_java 】

ReentrantReadWriteLockTest.java类

public class ReentrantReadWriteLockTest
{
	public static void test()
	{
		Bean bean = new Bean();
		bean.x = 0;
		ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
		WriteThread w1 = new WriteThread(0, bean, lock.writeLock());
		ReadThread r1 = new ReadThread(0, bean, lock.readLock());
		ReadThread r2 = new ReadThread(1, bean, lock.readLock());
		ReadThread r3 = new ReadThread(2, bean, lock.readLock());
		
		w1.start();
		r1.start();
		r2.start();
		r3.start();
	}
}

class Bean
{
	public int x;
	
}
class WriteThread extends Thread
{
	int id;
	Bean bean;
	Lock lock;

	public WriteThread(int id, Bean bean, Lock lock)
	{
		super();
		this.id = id;
		this.bean = bean;
		this.lock = lock;
	}

	@Override
	public void run()
	{
		for (int i = 0; i < 10; i++)
		{
			lock.lock();
			
			System.out.println("         write before sleep :" + id);
			try
			{
				Thread.sleep(1000);
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			bean.x = i;
			System.out.println("         write value :" + bean.x);
			
			System.out.println("         write after sleep :" + id);
			
			lock.unlock();
			
			try
			{
				Thread.sleep(1);//让出CPU
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	}
}


class ReadThread extends Thread
{
	int id;
	Bean bean;
	Lock lock;
	
	public ReadThread(int id, Bean bean, Lock lock)
	{
		super();
		this.id = id;
		this.bean = bean;
		this.lock = lock;
	}

	@Override
	public void run()
	{
		for (int i = 0; i < 10; i++)
		{
			lock.lock();
			
			System.out.println("Thread:"+ id +" Read before sleep :" + id);
			try
			{
				Thread.sleep(1000);
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			System.out.println("Thread:"+ id +" Read value :" + bean.x);
			
			System.out.println("Thread:"+ id +" Read after sleep :" + id);
			
			lock.unlock();
		}
	}
}

部分日志打印:

         write before sleep :0
         write value :0
         write after sleep :0
Thread:0 Read before sleep :0
Thread:1 Read before sleep :1
Thread:2 Read before sleep :2
Thread:1 Read value :0
Thread:1 Read after sleep :1
Thread:2 Read value :0
Thread:2 Read after sleep :2
Thread:0 Read value :0
Thread:0 Read after sleep :0

 通过分析日志,可以看出:

1)写的锁有效时,无法后去读取锁。

2)写的锁无效时,读取锁可以忽略掉,读取线程的执行顺序已经不收锁的控制,效率较高。

Leave a Reply

15 − 9 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据