synchronized用过吗?

synchronized可以上锁的对象有

普通方法

synchronized用在普通方法上时,上锁的是执行这个方法的对象。

public synchronized void increment(){
	this.count++;
}

静态方法

synchronized用在静态方法上时,上锁的是这个类的Class对象

public static synchronized void increment(){
	count++;
}

代码块

synchronized用在代码块上时,上锁的是括号中指定的对象,比如说当前对象this

public void increment(){
	synchronized (this){
		this.count++;
	}
}
posted @ 2025-05-12 23:32  kuki'  阅读(12)  评论(0)    收藏  举报