forked from CentMeng/JavaFrameTest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathListAdd1.java
More file actions
57 lines (46 loc) · 1.31 KB
/
Copy pathListAdd1.java
File metadata and controls
57 lines (46 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.msj.sync.waitnotify;
import java.util.ArrayList;
import java.util.List;
/**
* 一般实现方式:启动两个线程,线程1增加队列,线程2一直循环遍历,当队列数等于5的时候,终止线程2
* @author Vincent.M mengshaojie@188.com on 2017/3/13.
*/
public class ListAdd1 {
private volatile static List list = new ArrayList();
public void add(){
list.add("bjsxt");
}
public int size(){
return list.size();
}
public static void main(String[] args) {
final ListAdd1 list1 = new ListAdd1();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
for(int i = 0; i <10; i++){
list1.add();
System.out.println("当前线程:" + Thread.currentThread().getName() + "添加了一个元素..");
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "t1");
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
while(true){
if(list1.size() == 5){
System.out.println("当前线程收到通知:" + Thread.currentThread().getName() + " list size = 5 线程停止..");
throw new RuntimeException();
}
}
}
}, "t2");
t1.start();
t2.start();
}
}