forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT1.java
More file actions
48 lines (39 loc) · 1.16 KB
/
T1.java
File metadata and controls
48 lines (39 loc) · 1.16 KB
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
package com.basic; /**
* @program JavaBooks
* @description: synchronized关键字
* @author: mf
* @create: 2019/12/26 21:00
*/
/**
* 对某个对象加锁
*/
public class T1 {
private int count = 10;
private static int count1 = 10;
private Object o = new Object();
public void m() {
synchronized (o) { // 给o对象加锁, o是监视器
count--;
System.out.println(Thread.currentThread().getName() + " count = " + count);
}
}
public void m1() {
synchronized (this) { // 任何线程要执行下面的代码,必须先拿到this的锁
count--;
System.out.println(Thread.currentThread().getName() + " count = " + count);
}
}
public synchronized void m2() { // 等效synchroniezd(this)
count--;
System.out.println(Thread.currentThread().getName() + " count = " + count);
}
public static synchronized void m3() { // class对象
count1--;
System.out.println(Thread.currentThread().getName() + " count = " + count1);
}
public static void m4() {
synchronized (T1.class) {
count1--;
}
}
}