File tree Expand file tree Collapse file tree 3 files changed +82
-0
lines changed
main/java/cn/byhieg/threadtutorial/char03
test/java/cn/byhieg/threadtutorialtest/char03test Expand file tree Collapse file tree 3 files changed +82
-0
lines changed Original file line number Diff line number Diff line change 1+ package cn .byhieg .threadtutorial .char03 ;
2+
3+ /**
4+ * Created by byhieg on 17/1/15.
5+ * Mail to byhieg@gmail.com
6+ */
7+ public class CommonNotify {
8+
9+ private Object object ;
10+ public CommonNotify (Object object ){
11+ this .object = object ;
12+ }
13+
14+ public void doNotify (){
15+ synchronized (object ){
16+ System .out .println ("准备通知" );
17+ object .notifyAll ();
18+ System .out .println ("通知结束" );
19+ }
20+ }
21+ }
Original file line number Diff line number Diff line change 1+ package cn .byhieg .threadtutorial .char03 ;
2+
3+ /**
4+ * Created by byhieg on 17/1/15.
5+ * Mail to byhieg@gmail.com
6+ */
7+ public class CommonWait {
8+
9+ private Object object ;
10+ public CommonWait (Object object ){
11+ this .object = object ;
12+ }
13+
14+ public void doSomething () throws Exception {
15+ synchronized (object ){
16+ System .out .println ("begin wait " + Thread .currentThread ().getName ());
17+ object .wait ();
18+ System .out .println ("end wait " + Thread .currentThread ().getName ());
19+ }
20+ }
21+ }
Original file line number Diff line number Diff line change 1+ package cn .byhieg .threadtutorialtest .char03test ;
2+
3+ import cn .byhieg .threadtutorial .char03 .CommonNotify ;
4+ import cn .byhieg .threadtutorial .char03 .CommonWait ;
5+ import junit .framework .TestCase ;
6+
7+ /**
8+ * Created by byhieg on 17/1/15.
9+ * Mail to byhieg@gmail.com
10+ */
11+ public class CommonTest extends TestCase {
12+
13+ public void testRun () throws Exception {
14+ Object lock = new Object ();
15+ new Thread (()->{
16+ try {
17+ new CommonWait (lock ).doSomething ();
18+ } catch (Exception e ) {
19+ e .printStackTrace ();
20+ }
21+ }).start ();
22+
23+ new Thread (()->{
24+ try {
25+ new CommonWait (lock ).doSomething ();
26+ } catch (Exception e ) {
27+ e .printStackTrace ();
28+ }
29+ }).start ();
30+
31+ Thread .sleep (1000 );
32+
33+ new Thread (()->{
34+ new CommonNotify (lock ).doNotify ();
35+ }).start ();
36+
37+ Thread .sleep (1000 * 3 );
38+
39+ }
40+ }
You can’t perform that action at this time.
0 commit comments