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();
java之Synchronized(锁住对象和锁住代码)
最新推荐文章于 2024-09-29 10:25:17 发布