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

Commit cbcc154

Browse files
Create SimpleLock.java
1 parent ea4b7c7 commit cbcc154

File tree

1 file changed

+70
-0
lines changed
  • concurrency/src/main/java/com/javaedge/concurrency/example/aqs

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
public class SimpleLock {
2+
private static class Sync extends AbstractQueuedSynchronizer {
3+
@Override
4+
protected boolean tryAcquire(int ignore) {
5+
return compareAndSetState(0, 1);
6+
}
7+
8+
@Override
9+
protected boolean tryRelease(int ignore) {
10+
setState(0);
11+
return true;
12+
}
13+
14+
protected Sync() {
15+
super();
16+
}
17+
}
18+
19+
private final Sync sync = new Sync();
20+
21+
public void lock() {
22+
sync.acquire(1);
23+
}
24+
25+
public void unlock() {
26+
sync.release(1);
27+
}
28+
29+
private static class MyThread extends Thread {
30+
private final String name;
31+
private final SimpleLock lock;
32+
33+
private MyThread(String name, SimpleLock lock) {
34+
this.name = name;
35+
this.lock = lock;
36+
}
37+
38+
@Override
39+
public void run() {
40+
try {
41+
lock.lock();
42+
System.out.println(name + " get the lock");
43+
TimeUnit.SECONDS.sleep(2);
44+
} catch (InterruptedException e) {
45+
e.printStackTrace();
46+
} finally {
47+
lock.unlock();
48+
System.out.println(name + " release the lock");
49+
}
50+
}
51+
}
52+
53+
public static void main(String[] args) {
54+
final SimpleLock mutex = new SimpleLock();
55+
MyThread t1 = new MyThread("t1", mutex);
56+
MyThread t2 = new MyThread("t2", mutex);
57+
MyThread t3 = new MyThread("t3", mutex);
58+
t1.start();
59+
t2.start();
60+
t3.start();
61+
try {
62+
t1.join();
63+
t2.join();
64+
t3.join();
65+
} catch (InterruptedException e) {
66+
e.printStackTrace();
67+
}
68+
System.out.println("main thread exit!");
69+
}
70+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /