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 获得锁和释放锁的方式不同,应该不能混合使用


  • 1

Reply