-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLockObject.java
More file actions
executable file
·87 lines (70 loc) · 1.82 KB
/
LockObject.java
File metadata and controls
executable file
·87 lines (70 loc) · 1.82 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package basic.thread.lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 1.����ʵ��ͬ������,���ǵ�ǰʵ������. 2.���ھ�̬ͬ������,���ǵ�ǰ�����Class����.
* 3.����ͬ��������,����Synchonized���������õĶ���.
*
* @author yangqc
*/
public class LockObject {
private static ReentrantLock lock = new ReentrantLock();
private static volatile int a = 0;
synchronized static int get() throws InterruptedException {
Thread.sleep(5000);
return a;
}
synchronized static void put(int b) {
a = b;
}
public static void main(String[] args) {
Runnable task1 = () -> {
try {
System.out.println(LockObject.get());
} catch (InterruptedException e) {
System.out.println("fuck,interrupted!");
}
};
Runnable task2 = () -> {
LockObject.put(12);
System.out.println("completed");
};
// new Thread(task1).start();
// new Thread(task2).start();
new Thread(new Task(true)).start();
new Thread(new Task(false)).start();
}
}
class A {
public synchronized void printName() throws InterruptedException {
while (true) {
Thread.sleep(1000);
System.out.println("name");
}
}
public synchronized void printAge() throws InterruptedException {
while (true) {
Thread.sleep(1000);
System.out.println("age");
}
}
}
class Task implements Runnable {
private final boolean flag;
private A a;
Task(boolean flag) {
this.flag = flag;
a = new A();
}
@Override
public void run() {
try {
if (flag) {
a.printAge();
} else {
a.printName();
}
} catch (Exception e) {
System.out.println("fuck,interrupted!");
}
}
}