多线程之 对象锁的理解

package function.thread;

class AA{

}

class ThreadDemo extends Thread {

// 共享一个静态数据成员

private static String a = "" ;

ThreadDemo() {

}

ThreadDemo(String szName) {

super(szName);

}

public void run() {

// 为了更清楚地看到不正确的结果,这里放一个大的循环

if (this.getName().equals("Thread1")) {

System.out.println(this.getName()+" enter synchronized before.....\n");

synchronized (a) {

System.out.println(this.getName()+" enter.....");

// 为了演示产生的问题,这里设置一次睡眠

try {

for(int i = 0;i<10;i++){

System.out.println(this.getName()+" print ....");

Thread.sleep(200);

}

} catch (InterruptedException e) {

}

// 输出结果

System.out.println(this.getName()+" go off.....\n");

}

} else if (this.getName().equals("Thread2")) {

try {

for(int j =0;j<10;j++){

System.out.println(this.getName()+" enter synchronized before....."+j);

Thread.sleep(200);

}

} catch (InterruptedException e) {

e.printStackTrace();

}

synchronized (a) {

System.out.println(this.getName()+" enter.....");

// 为了演示产生的问题,这里设置一次睡眠

try {

for(int i = 0;i<10;i++){

System.out.println(this.getName()+" print......");

Thread.sleep(200);

}

} catch (InterruptedException e) {

}

// 输出结果

System.out.println(this.getName()+" go off.....\n");

}

}

}

}

public class ThreadSync {

public static void main(String args[]) {

ThreadDemo th1 = new ThreadDemo("Thread1");

ThreadDemo th2 = new ThreadDemo("Thread2");

th1.start();

th2.start();

}

}

 

运行结果:

Thread1 enter synchronized before.....

Thread2 enter synchronized before.....0

Thread1 enter.....

Thread1 print ....

Thread1 print ....

Thread2 enter synchronized before.....1

Thread2 enter synchronized before.....2

Thread1 print ....

Thread1 print ....

Thread2 enter synchronized before.....3

Thread1 print ....

Thread2 enter synchronized before.....4

Thread1 print ....

Thread2 enter synchronized before.....5

Thread1 print ....

Thread2 enter synchronized before.....6

Thread1 print ....

Thread2 enter synchronized before.....7

Thread1 print ....

Thread2 enter synchronized before.....8

Thread1 print ....

Thread2 enter synchronized before.....9

Thread1 go off.....

Thread2 enter.....

Thread2 print......

Thread2 print......

Thread2 print......

Thread2 print......

Thread2 print......

Thread2 print......

Thread2 print......

Thread2 print......

Thread2 print......

Thread2 print......

Thread2 go off.....

 

说明:在进入synchronized 块之前,线程不会被阻塞。

比喻:多个人进入一个房间,房间好比是共享的,房间的钥匙好比是锁

猜你喜欢

转载自zengshaotao.iteye.com/blog/2372263
今日推荐