先上结论:
类方法中,synchronized锁住的是对象this,只有调用同一个对象的方法才需要获取锁。同时,同一个对象中所有加了synchronize的方法只能一次调用一个
静态方法中,synchronized锁的是整个类对象,类似于(X.class),该类中所有加了synchronized的静态方法,一次只能调用一个
class Sync {
public synchronized void test() {
System.out.println("test开始..");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test结束..");
}
public synchronized void test2() {
System.out.println("test2开始..");
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test2结束..");
}
}
class MyThread extends Thread {
private Sync sync;
public MyThread(Sync sync) {
this.sync = sync;
}
public void run() {
sync.test();
}
}
class MyThread2 extends Thread {
private Sync sync;
public MyThread2(Sync sync) {
this.sync = sync;
}
public void run() {
sync.test2();
}
}
public class Main {
public static void main(String[] args) {
Sync sync = new Sync();
Thread thread = new MyThread(sync);
Thread thread2 = new MyThread2(sync);
thread.start();
thread2.start();
}
}
运行结果:
test开始..
test结束..
test2开始..
test2结束..
方案是按顺序执行的,说明了锁住的是同一个对象:
main方法换成以下写法:
public static void main(String[] args) {
Thread thread = new MyThread(new Sync());
Thread thread2 = new MyThread2(new Sync());
thread.start();
thread2.start();
}
结果:
test开始..
test2开始..
test2结束..
test结束..
synchronized没有起到同步作用,说明不是同一个锁
静态方法:
class Sync {
public static synchronized void test() {
System.out.println("test开始..");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test结束..");
}
public static synchronized void test2() {
System.out.println("test2开始..");
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test2结束..");
}
}
class MyThread extends Thread {
public void run() {
Sync.test();
}
}
class MyThread2 extends Thread {
public void run() {
Sync.test2();
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new MyThread();
Thread thread2 = new MyThread2();
thread.start();
thread2.start();
}
}
运行结果:
test开始..
test结束..
test2开始..
test2结束..
本文参考了叉叉哥 的博客:Java线程同步:synchronized锁住的是代码还是对象