Java中synchronized用在静态方法和非静态方法上面的区别
在Java中,synchronized是用来表示同步的,我们可以synchronized来修饰一个方法。也可以synchronized来修饰方法里面的一个语句块。那么,在static方法和非static方法前面加synchronized到底有什么不同呢?大家都知道,static的方法属于类方法,它属于这个Class(注意:这里的Class不是指Class的某个具体对象),那么static获取到的锁,是属于类的锁。而非static方法获取到的锁,是属于当前对象的锁。所以,他们之间不会产生互斥。
上代码
package TestSynchronizedStaticOrNot;
public class TestSynchronizedStaticOrNot {
public static synchronized void staticFunction(String name)
throws InterruptedException {
for (
int i =
0; i <
3; i++) {
Thread.sleep(
1000);
System.out.println(name +
" --- static function running ...");
}
}
public synchronized void function(String name)
throws InterruptedException {
for (
int i =
0; i <
3; i++) {
Thread.sleep(
1000);
System.out.println(name +
" +++ function running ...");
}
}
public static void main(String[] args) {
final TestSynchronizedStaticOrNot demo =
new TestSynchronizedStaticOrNot();
Thread thread1 =
new Thread(
new Runnable() {
@Override
public void run() {
try {
staticFunction(
"1");
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread11 =
new Thread(
new Runnable() {
@Override
public void run() {
try {
staticFunction(
"2");
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 =
new Thread(
new Runnable() {
@Override
public void run() {
try {
demo.function(
"1");
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread23 =
new Thread(
new Runnable() {
@Override
public void run() {
try {
demo.function(
"12");
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread22 =
new Thread(
new Runnable() {
@Override
public void run() {
try {
new TestSynchronizedStaticOrNot().function(
"2");
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread11.start();
thread1.start();
thread2.start();
thread23.start();
thread22.start();
}
}
根据结果很容分析到,加在类上面的锁,加载对象上面的锁。如果上了对象锁,同一个对象是不能再获取锁的,必须等待释放,如果是不同的实例还是可以去获取锁的。
那当我们想让所有这个类下面的方法都同步的时候,也就是让所有这个类下面的静态方法和非静态方法共用同一把锁的时候,我们如何办呢?此时我们可以使用Lock。