File tree Expand file tree Collapse file tree 4 files changed +109
-0
lines changed
src/main/java/com/chen/api/util/thread/study/chapter3/twoThreadTransData Expand file tree Collapse file tree 4 files changed +109
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .chen .api .util .thread .study .chapter3 .twoThreadTransData ;
2+
3+ import java .util .ArrayList ;
4+ import java .util .List ;
5+
6+ /**
7+ * @author chen weijie
8+ * @date 2018-04-23 12:13 AM
9+ */
10+ public class MyList {
11+
12+
13+ private List list = new ArrayList ();
14+
15+ public void add () {
16+ list .add ("高" );
17+ }
18+
19+ public int size () {
20+
21+ return list .size ();
22+ }
23+
24+ }
Original file line number Diff line number Diff line change 1+ package com .chen .api .util .thread .study .chapter3 .twoThreadTransData ;
2+
3+ /**
4+ * 虽然两个线程间实现了通信,但是b线程一直在while循环检测一个条件,此时会浪费cpu资源.
5+ *
6+ * @author chen weijie
7+ * @date 2018-04-23 12:19 AM
8+ */
9+ public class Test {
10+
11+ public static void main (String [] args ) {
12+
13+ MyList list = new MyList ();
14+
15+ ThreadA threadA = new ThreadA (list );
16+ threadA .setName ("a" );
17+ threadA .start ();
18+
19+ ThreadB threadB = new ThreadB (list );
20+ threadB .setName ("b" );
21+ threadB .start ();
22+
23+ }
24+
25+
26+ }
Original file line number Diff line number Diff line change 1+ package com .chen .api .util .thread .study .chapter3 .twoThreadTransData ;
2+
3+ /**
4+ * @author chen weijie
5+ * @date 2018-04-23 12:14 AM
6+ */
7+ public class ThreadA extends Thread {
8+
9+
10+ private MyList list ;
11+
12+ public ThreadA (MyList list ) {
13+ super ();
14+ this .list = list ;
15+ }
16+
17+ @ Override
18+ public void run () {
19+ for (int i = 0 ; i < 100 ; i ++) {
20+ list .add ();
21+ System .out .println ("list 添加了" + (i + 1 ) + "个元素" );
22+ try {
23+ Thread .sleep (1000 );
24+ } catch (InterruptedException e ) {
25+ e .printStackTrace ();
26+ }
27+ }
28+ }
29+
30+ }
Original file line number Diff line number Diff line change 1+ package com .chen .api .util .thread .study .chapter3 .twoThreadTransData ;
2+
3+ /**
4+ *
5+ *
6+ * @author chen weijie
7+ * @date 2018-04-23 12:17 AM
8+ */
9+ public class ThreadB extends Thread {
10+
11+ private MyList list ;
12+
13+ public ThreadB (MyList list ) {
14+ super ();
15+ this .list = list ;
16+ }
17+
18+ @ Override
19+ public void run () {
20+ while (true ) {
21+ System .out .println ("b线程running....." );
22+ if (list .size () == 5 ) {
23+ System .out .println ("==5了,线程b要退出了." );
24+ throw new RuntimeException ();
25+ }
26+ }
27+ }
28+
29+ }
You can’t perform that action at this time.
0 commit comments