voctor动态数组、同步类容器,底层实现基于:Collections.synchronized
x
1
package demo5;
2
3
import java.util.ArrayList;
4
import java.util.Collections;
5
import java.util.List;
6
import java.util.Vector;
7
8
/**
9
* Created by liudan on 2017/7/9.
10
*/
11
public class MyThread2 extends Thread {
12
/*同步类容器、动态数组*/
13
public static void main(String[] args) {
14
/*final Vector<String> ticksts = new Vector<>();*/
15
16
List<String> ticksts = Collections.synchronizedList(new ArrayList<String>());
17
18
19
for (int i = 1; i <= 100; i++) {
20
ticksts.add("G1001-火车票-G000X" + i);
21
}
22
23
24
for (int i = 1; i <= 10; i++) {
25
new Thread("线程" + i) {
26
27
public void run() {
28
while (true) {
29
if (ticksts.isEmpty()) break;
30
System.err.println(Thread.currentThread().getName() + " " + ticksts.remove(0));
31
}
32
}
33
}.start();
34
}
35
36
}
37
}
38
输出:
39
线程001 G1001-火车票-G000X1
40
线程001 G1001-火车票-G000X2
41
线程001 G1001-火车票-G000X3
42
线程001 G1001-火车票-G000X4
43
线程002 G1001-火车票-G000X5
44
线程002 G1001-火车票-G000X7
45
线程001 G1001-火车票-G000X6
46
线程001 G1001-火车票-G000X9
47
线程001 G1001-火车票-G000X10
48
线程002 G1001-火车票-G000X8