Discuss / Java / 练习

练习

Topic source

狠美味2013

#1 Created at ... [Delete] [Delete and Lock User]
练习

package com.itranswarp.world;

/**

 * 测试专用

 * 

 * @author hadoop

 * 

 */

public class Main {

static final Object LOCK_A = new Object();

static final Object LOCK_B = new Object();

public static void main(String[] args) {

new Thread1().start();

new Thread2().start();

}

static void sleep1s() {

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

class Thread1 extends Thread {

public void run() {

System.out.println("Thread-1: try get lock A...");

synchronized (Main.LOCK_A) {

System.out.println("Thread-1: lock A got.");

Main.sleep1s();

System.out.println("Thread-1: try get lock B...");

synchronized (Main.LOCK_B) {

System.out.println("Thread-1: lock B got.");

Main.sleep1s();

}

System.out.println("Thread-1: lock B released.");

}

System.out.println("Thread-1: lock A released.");

}

}

class Thread2 extends Thread {

public void run() {

System.out.println("Thread-2: try get lock A...");

synchronized (Main.LOCK_A) {

System.out.println("Thread-2: lock A got.");

Main.sleep1s();

System.out.println("Thread-2: try get lock B...");

synchronized (Main.LOCK_B) {

System.out.println("Thread-2: lock B got.");

Main.sleep1s();

}

System.out.println("Thread-2: lock B released.");

}

System.out.println("Thread-2: lock A released.");

}

}

我运行的结果是

Thread-1: try get lock A...
Thread-1: lock A got.
Thread-2: try get lock A...
Thread-1: try get lock B...
Thread-1: lock B got.
Thread-1: lock B released.
Thread-2: lock A got. 
Thread-1: lock A released.
Thread-2: try get lock B...
Thread-2: lock B got.
Thread-2: lock B released.
Thread-2: lock A released.

其中对

Thread-2: lock A got. 
Thread-1: lock A released.

两行有点疑惑,乍一看好像Thread-2在Thread-1释放lock A前就已经获取了lock A,但其实在执行

System.out.println("Thread-1: lock A released.");

这句前Thread-1就已经释放了lock A,只是之后CPU先执行了Thread-2的

System.out.println("Thread-2: lock A got.");

Thread-2随即被sleep,CPU再去执行"Thread-1: lock A released."那句,可否这样理解?

因该是的吧,线程1在获取锁A后,在

		synchronized (Main.LOCK_A) {
			System.out.println("Thread-1: lock A got.");
			Main.sleep1s();
			System.out.println("Thread-1: try get lock B...");
			synchronized (Main.LOCK_B) {
				System.out.println("Thread-1: lock B got.");
				Main.sleep1s();
			}
			System.out.println("Thread-1: lock B released.");
		}

结尾就已经释放,所以线程2获取锁A和

System.out.println("Thread-1: lock A released.");

的先后顺序并不确定

HeggyChan

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

synchronized 是可重入锁啊  获取的是同个实例  没毛病啊


  • 1

Reply