Java中线程同步的synchronized()(同步方法块)这个括号里的参数是啥?

有的时候写的this,这个this指的是什么?有的又像是随便取的名字比如objA,这个objA是一个什么类型的对象啊?

synchronized()、synchronized(this)、synchronized(类名.class)
synchronized加在非静态方法前和synchronized(this)都是锁住了这个类的对象,如果多线程访问,对象不同,就锁不住,对象固定是一个,就可锁住。
synchronized(类名.class)和加在静态方法前,是锁住了代码块,不管多线程访问的时候对象是不是同一个,能缩小代码段的范围就尽量缩小,能在代码段上加同步就不要再整个方法上加同步,缩小锁的粒度。追问

我还是不太理解,我只知道当当锁加在一个方法上就是当一个线程用这个方法时其他线程就不能用了,那这个锁方法块里面的参数是干嘛用的我完全不能理解😭

追答

自己感受一下

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(); 
}
else if (mType == 3) {
mTest.testThird(); 
}
}
}
}


public static void main(String[] args) {
Synchronized syn = new Synchronized();
Test test = syn.new Test();
for (int i = 0; i < 5; ++i) {
syn.new TestThread(1, null).start();
}
}
}

追问

实在抱歉我还不太能理解😭为什么会有object对象放在括号里?这个object对象起什么作用?

温馨提示:答案为网友推荐,仅供参考
相似回答