好记性不如铅笔头

java, think_in_java, 编程

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

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

github:

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

ReentrantLockTest.java类

public class ReentrantLockTest
{
	public static void test()
	{
		ReentrantLock lock = new ReentrantLock();

		ReetThread t1 = new ReetThread(1,lock);
		ReetThread t2 = new ReetThread(2,lock);
		ReetThread t3 = new ReetThread(3,lock);
		
		t1.start();
		t2.start();
		t3.start();
	}

}
class ReetThread extends Thread
{
	int id;
	ReentrantLock lock;
	public ReetThread(int id, ReentrantLock lock)
	{
		super();
		this.id = id;
		this.lock = lock;
	}

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

有lock/unlock运行结果:

before sleep :1
after sleep :1
before sleep :2
after sleep :2
before sleep :2
after sleep :2
before sleep :3
after sleep :3
before sleep :3
after sleep :3
before sleep :1
after sleep :1

从日志可以看出,即使线程休眠,也无法打乱线程的执行顺序。

注释掉A,B两行代码运行结果:

before sleep :1
before sleep :3
before sleep :2
after sleep :1
after sleep :2
after sleep :3
before sleep :3
before sleep :2
before sleep :1
after sleep :3
after sleep :1
after sleep :2

从日志可以看出线程的执行顺序已经混乱了。

 备注:

1)ReentrantLock是可重用锁,这个实例并没有具体描述这点。

2)

Leave a Reply

3 × 1 =

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