赞
踩
1、问题
Synchronized我们一般都知道是锁,但是我们怎么区分是锁对象还是锁代码呢?
2、测试Demo
package leetcode.chenyu.test;
public class Synchronized {
class Test {
public synchronized void testFirst() {
print("testFirst");
}
public void testSecond() {
synchronized(this) {
print("testSecond");
}
}
public void testThird() {
synchronized(Test.class) {
print("testThird");
}
}
public void print(String method) {
System.out.println(method + "start");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(method + "end");
}
}
class TestThread extends Thread {
public int mType = 0;
public Test mTest = null;
public TestThread(int type, Test test) {
this.mType = type;
this.mTest = test;
}
public void run() {
if (mTest == null) {
if (mType == 1) {
Test test = new Test();
test.testFirst();
}
else if (mType == 2) {
Test test = new Test();
test.testSecond();
}
else if (mType == 3) {
Test test = new Test();
test.testThird();
}
} else {
if (mType == 1) {
mTest.testFirst();
}
else if (mType == 2) {
mTest.testSecond();
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。