forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT5.java
More file actions
46 lines (36 loc) · 1.12 KB
/
T5.java
File metadata and controls
46 lines (36 loc) · 1.12 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
package com.basic;
import java.util.concurrent.TimeUnit;
/**
* @program JavaBooks
* @description: 异常释放锁
* @author: mf
* @create: 2019/12/27 23:38
*/
public class T5 {
private int count = 0;
public synchronized void m() {
System.out.println(Thread.currentThread().getName() + " start... ");
while (true) {
count++;
System.out.println(Thread.currentThread().getName() + " count = " + count);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (count == 5) {
int i = 1 / 0; // 此处抛出异常,锁将被释放,要想不被释放,可以在这里进行catch,然后让循环继续
}
}
}
public static void main(String[] args) {
T5 t5 = new T5();
new Thread(() -> t5.m(), "t1").start();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> t5.m(), "t2").start();
}
}