Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit83db082

Browse files
committed
Lock examples
1 parentc1117a9 commit83db082

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
packagecom.winterbe.java8.samples.concurrent;
2+
3+
importjava.util.concurrent.ExecutorService;
4+
importjava.util.concurrent.Executors;
5+
importjava.util.concurrent.locks.ReentrantLock;
6+
importjava.util.stream.IntStream;
7+
8+
/**
9+
* @author Benjamin Winterberg
10+
*/
11+
publicclassLock1 {
12+
13+
privatestaticfinalintNUM_INCREMENTS =10000;
14+
15+
privatestaticReentrantLocklock =newReentrantLock();
16+
17+
privatestaticintcount =0;
18+
19+
privatestaticvoidincrement() {
20+
lock.lock();
21+
try {
22+
count++;
23+
}
24+
finally {
25+
lock.unlock();
26+
}
27+
}
28+
29+
publicstaticvoidmain(String[]args) {
30+
testLock();
31+
}
32+
33+
privatestaticvoidtestLock() {
34+
count =0;
35+
36+
ExecutorServiceexecutor =Executors.newFixedThreadPool(2);
37+
38+
IntStream.range(0,NUM_INCREMENTS)
39+
.forEach(i ->executor.submit(Lock1::increment));
40+
41+
ConcurrentUtils.stop(executor);
42+
43+
System.out.println(count);
44+
}
45+
46+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
packagecom.winterbe.java8.samples.concurrent;
2+
3+
importjava.util.concurrent.ExecutorService;
4+
importjava.util.concurrent.Executors;
5+
importjava.util.concurrent.locks.ReentrantLock;
6+
7+
/**
8+
* @author Benjamin Winterberg
9+
*/
10+
publicclassLock2 {
11+
12+
publicstaticvoidmain(String[]args) {
13+
ExecutorServiceexecutor =Executors.newFixedThreadPool(2);
14+
15+
ReentrantLocklock =newReentrantLock();
16+
17+
executor.submit(() -> {
18+
lock.lock();
19+
try {
20+
System.out.println(lock.isLocked());
21+
}finally {
22+
lock.unlock();
23+
}
24+
});
25+
26+
ConcurrentUtils.stop(executor);
27+
}
28+
29+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp