---
title: "同一任务和对象锁的问题"
author: "maozj"
date: "2010-08-04T08:31:02Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-08-04T08:31:35Z"
id: 728485
url: "https://maozj.iteye.com/blog/728485"
---

偶尔翻开java编程思想看看多线程的篇章，意焦突然卡在某个问题上不动了。这个问题看过多少次多少遍了，此刻才领会，顿时感觉自己好笨拙的思维。

    问题是这样的：一般来说，在多线程程序中，某个任务在持有某对象的锁后才能运行任务，其他任务只有在该任务释放同一对象锁后才能拥有对象锁，然后执行任务。于是，想到，同一个任务在持有同一个对象的锁后，在不释放锁的情况下，继续调用同一个对象的其他同步(synchronized)方法，该任务是否会再次持有该对象锁呢？

    答案是肯定的。<span style="color:red">同一个任务在调用同一个对象上的其他synchronized方法，可以再次获得该对象锁。</span>

    多线程编程是一件很微妙的事情，这里考验人的不是大局而是细节，细节的细节。希望能唤醒自己愚笨的思维。

 
```java
 package thread.thread1;

/**
 * 同一任务可以再次持有对象锁 create on 2010.08.04 08:27
 * 
 * @since jdk1.6
 * @author maozj
 * @version 1.0
 * 
 */
public class SynchronizedClassHolder {
	/**
	 * Test client
	 * @param args
	 */
	public static void main(String[] args) {
		new Thread() {
			public void run() {
				new SynchronizedClassHolder().f1();
			}
		}.start();
	}

	private static int count = 10;

	/**
	 * synchronized f1()
	 */
	public synchronized void f1() {
		if (--count > 0) {
			System.out.println("f1() calling f2() count " + count);
			f2();
		}
	}

	/**
	 * synchronized f2()
	 */
	public synchronized void f2() {
		if (--count > 0) {
			System.out.println("f2() calling f1() count " + count);
			f1();
		}
	}
}

输出：
f1() calling f2() count 9
f2() calling f1() count 8
f1() calling f2() count 7
f2() calling f1() count 6
f1() calling f2() count 5
f2() calling f1() count 4
f1() calling f2() count 3
f2() calling f1() count 2
f1() calling f2() count 1

```