Discuss / Java / ReentrantLock还没释放锁时,其他线程也可以获取当前对象锁吗?

ReentrantLock还没释放锁时,其他线程也可以获取当前对象锁吗?

Topic source

森屿54662

#1 Created at ... [Delete] [Delete and Lock User]
public class ReentrantLockTest {
	public static void main(String[] args) {
		Count count = new Count();
		new Thread() {
			public void run() {
				count.add(1);
			}
		}.start();
		new Thread() {
			public void run() {
				count.addd(2);
			}
		}.start();
	}
}

class Count {
	private int m = 0;
	private final Lock lock = new ReentrantLock();

	public void add(int n) {
		lock.lock();
		System.out.println("获取锁");
		try {
			m += n;
			try {
				System.out.println("thread1等待3秒");
				Thread.sleep(3000);
				System.out.println("thread1结束3秒");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} finally {
			lock.unlock();
			System.out.println("释放锁");
		}
	}

	public synchronized void addd(int n) {
		System.out.println("获取锁222");
		m += n;
		System.out.println("释放锁222");
	}

	public void getM() {
		System.out.println(m);
	}
}

执行结果是这样的:

获取锁
thread1等待3秒
获取锁222
释放锁222
thread1结束3秒
释放锁

在线程1等待3秒过程中,线程2执行了addd方法?

还是我哪里有问题希望指正,谢谢

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

只能说明你的两个线程获取的不是同一个锁

茂茂_916

#3 Created at ... [Delete] [Delete and Lock User]

synchronized 和 ReentrantLock 获得锁和释放锁的方式不同,应该不能混合使用

Frank8y

#4 Created at ... [Delete] [Delete and Lock User]

ReentrantLock方式的锁对象是构造出来的lock对象;

private final Lock lock = new ReentrantLock();

而synchronized的锁对象构造出来的count对象

Count count = new Count();

云外方天

#5 Created at ... [Delete] [Delete and Lock User]

看了半天才发现,你add()方法使用ReentrantLock作为锁,addd()使用synchronized(this)作为锁,两个方法的锁对象不一样,当然无法实现同步锁功能了。

synchronized的锁对象是内部锁intrinsicLock,Java中每一个对象都有一个内部锁,和ReentrantLock是不一样的锁。


  • 1

Reply