-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWindow2_1.java
More file actions
48 lines (46 loc) · 1.38 KB
/
Window2_1.java
File metadata and controls
48 lines (46 loc) · 1.38 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 org.cp;
/**
* 实现接口方式线程
* 同步代码块 线程安全
* create by CP on 2019/7/25 0025.
*/
public class Window2_1 implements Runnable {
private static int ticket = 100;
private Object o1 = new Object();
private static Object o2 = new Object();
@Override
public void run() {
while (true) {
//Window对象只有一个,所以是不是静态对象锁都可以
// synchronized (o1) {
// synchronized (o2) {
synchronized (this) {
if (ticket>0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+ ": "+ticket);
ticket--;
} else {
break;
}
}
}
}
}
class WindowTest2_1 {
public static void main(String[] args) {
Window2_1 window = new Window2_1();
Thread window1 = new Thread(window);
Thread window2 = new Thread(window);
Thread window3 = new Thread(window);
window1.setName("窗口1 ");
window2.setName("窗口2 ");
window3.setName("窗口3 ");
window1.start();
window2.start();
window3.start();
}
}