Java多线程synchronized

synchronized依靠锁机制实现多线程的同步,锁分两种

  • 对象锁
  • 类锁

1.synchronized作用于普通方法时依靠对象锁工作,多线程访问synchronized方法,一旦某个线程抢到锁后,其他进程排队等待
等效于

1
2
3
4
void method{
synchronized(this){
}
}

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public class TestSynchronized {
public synchronized void method1() throws InterruptedException {
System.out.println("Method1 start at :" + System.currentTimeMillis());
Thread.sleep(6000);
System.out.println("Method1 end at :" + System.currentTimeMillis());
}
public synchronized void method2() throws InterruptedException {
while (true) {
System.out.println("method2 running");
Thread.sleep(200);
}
}
static TestSynchronized instance = new TestSynchronized();
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
instance.method1();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 1; i < 4; i++) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread1 still alive");
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try {
instance.method2();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
thread1.start();
thread2.start();
}
}

方法method2会一直等待method1执行完成后再执行。
synchronized void method(){}整个函数加上synchronized块,效率并不好。

2.synchronized作用于静态方法相当于

1
2
3
4
void method(){
synchronized(Object.class){
}
}
如果您觉得对您有帮助,谢谢您的赞赏!