forked from coderbruis/JavaSourceCodeLearning
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwinsLockTeset.java
More file actions
51 lines (45 loc) · 1.3 KB
/
TwinsLockTeset.java
File metadata and controls
51 lines (45 loc) · 1.3 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
package com.learnjava.concurrent;
import com.learnjava.concurent.TwinsLock;
import org.junit.Test;
import java.util.concurrent.locks.Lock;
/**
* @author LuoHaiYang
*/
public class TwinsLockTeset {
@Test
public void test() {
final Lock lock = new TwinsLock();
class Worker extends Thread {
public void run() {
while (true) {
lock.lock();
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName());
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
// 启动10个线程
for (int i = 0; i < 10; i++) {
Worker worker = new Worker();
worker.setName("Thread-" + i);
//worker.setDaemon(true);
worker.start();
}
// 每隔10秒换行
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
System.out.println();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}