Skip to content

Commit 4f398ad

Browse files
committed
添加chapter3
1 parent f6dc0bc commit 4f398ad

File tree

4 files changed

+109
-0
lines changed

4 files changed

+109
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
}

0 commit comments

Comments
 (0)