forked from zhaoshiling1017/ThreadProject
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyReentrantLock.java
More file actions
47 lines (39 loc) · 1.15 KB
/
Copy pathMyReentrantLock.java
File metadata and controls
47 lines (39 loc) · 1.15 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
package com.unicss;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
public class MyReentrantLock extends Thread {
TestReentrantLock lock;
private int id;
public MyReentrantLock(int i, TestReentrantLock test) {
this.id = i;
this.lock = test;
}
@Override
public void run() {
lock.print(id);
}
public static void main(String args[]) {
ExecutorService service = Executors.newCachedThreadPool();
TestReentrantLock lock = new TestReentrantLock();
for (int i = 0; i < 10; i++) {
service.submit(new MyReentrantLock(i, lock));
}
service.shutdown();
}
}
class TestReentrantLock {
private ReentrantLock lock = new ReentrantLock();
public void print(int str) {
try {
lock.lock();
System.out.println(str + "获得");
Thread.sleep((int) (Math.random() * 1000));
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println(str + "释放");
lock.unlock();
}
}
}