-
Notifications
You must be signed in to change notification settings - Fork 7
/
VectorExample1.java
64 lines (55 loc) · 1.82 KB
/
VectorExample1.java
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
58
59
60
61
62
63
64
package com.will.highconcurrency.example.syncContainer;
import com.will.highconcurrency.annoations.NotThreadSafe;
import com.will.highconcurrency.annoations.ThreadSafe;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* Created by Will.Zhang on 2018/3/22 0022 17:09.
*/
@ThreadSafe
public class VectorExample1 {
//线程数
public static int clientTotal = 5000;
//并发数
public static int threadTotal = 200;
/*
vector是线程同步的
虽然说是同步的, 但并不代表是安全的
下一个例子会说明
*/
private static Vector<Integer> vector = new Vector<>();
//private static List<Integer> list = new Vector<>();
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(threadTotal);
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
for (int i = 0; i < clientTotal; i++) {
final int count = i;
executorService.execute(() -> {
try {
semaphore.acquire();
update(count);
semaphore.release();
} catch (Exception e) {
e.printStackTrace();
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
System.out.println("size : " + vector.size());
}
/**
* 往vector添加值
* @param i
*/
private static void update(int i){
vector.add(i);
}
}