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 12b84e3

Browse files
create UnsafeTest
1 parent 4e0b6e1 commit 12b84e3

File tree

1 file changed

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

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
public class UnsafeTest {
2+
3+
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
4+
Field f = Unsafe.class.getDeclaredField("theUnsafe");
5+
f.setAccessible(true);
6+
Unsafe unsafe = (Unsafe) f.get(null);
7+
Thread t1 = new Thread() {
8+
@Override
9+
public void run() {
10+
Thread.currentThread().setName("t1");
11+
System.out.println(Thread.currentThread().getName() + " before park");
12+
//park 100 seconds
13+
unsafe.park(false, TimeUnit.NANOSECONDS.convert(100, TimeUnit.SECONDS));
14+
System.out.println(Thread.currentThread().getName() + " after park");
15+
}
16+
};
17+
Thread t2 = new Thread() {
18+
@Override
19+
public void run() {
20+
try {
21+
Thread.currentThread().setName("t2");
22+
TimeUnit.SECONDS.sleep(1);
23+
System.out.println(Thread.currentThread().getName() + " unpark t1");
24+
unsafe.unpark(t1);
25+
} catch (InterruptedException e) {
26+
e.printStackTrace();
27+
}
28+
29+
}
30+
};
31+
Thread t3 = new Thread() {
32+
@Override
33+
public void run() {
34+
Thread.currentThread().setName("t3");
35+
System.out.println(Thread.currentThread().getName() + " park 5 seconds");
36+
//park 5 seconds
37+
unsafe.park(true, System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5,TimeUnit.SECONDS));
38+
System.out.println(Thread.currentThread().getName() + " after park");
39+
}
40+
};
41+
t1.start();
42+
t2.start();
43+
t3.start();
44+
try {
45+
t1.join();
46+
t2.join();
47+
t3.join();
48+
} catch (InterruptedException e) {
49+
e.printStackTrace();
50+
}
51+
}
52+
}

0 commit comments

Comments
(0)

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