-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathThreadLocalPerformance.java
More file actions
66 lines (58 loc) · 2.02 KB
/
Copy pathThreadLocalPerformance.java
File metadata and controls
66 lines (58 loc) · 2.02 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
58
59
60
61
62
63
64
65
66
package ch4.s3;
import java.util.Random;
import java.util.concurrent.*;
public class ThreadLocalPerformance {
public static final int GEN_COUNT = 10000000;
public static final int THREAD_COUNT = 4;
static ExecutorService exe = Executors.newFixedThreadPool(THREAD_COUNT);
public static Random rnd = new Random(123);
public static ThreadLocal<Random> tRnd = new ThreadLocal<Random>(){
protected Random initialValue() {
return new Random(123);
}
};
public static class RndTask implements Callable<Long>{
private int mode = 0;
public RndTask(int mode){
this.mode = mode;
}
public Random getRandom(){
if(mode == 0){
return rnd;
} else if (mode == 1){
return tRnd.get();
} else{
return null;
}
}
public Long call() throws Exception {
long b =System.currentTimeMillis();
for(long i=0;i<GEN_COUNT;i++){
getRandom().nextInt();
}
long e =System.currentTimeMillis();
System.out.println(Thread.currentThread().getName() + " spend" + (e-b) + "ms");
return e - b;
}
}
public static void main(String []args) throws ExecutionException, InterruptedException {
Future<Long>[] futs = new Future[THREAD_COUNT];
for(int i=0;i<THREAD_COUNT;i++){
futs[i] = exe.submit(new RndTask(0));
}
long totaltime = 0;
for(int i=0;i<THREAD_COUNT;i++){
totaltime += futs[i].get();
}
System.out.println("多线程访问同一个Random实例:"+ totaltime + "ms");
for(int i=0;i<THREAD_COUNT;i++){
futs[i] = exe.submit(new RndTask(1));
}
totaltime = 0;
for(int i=0;i<THREAD_COUNT;i++){
totaltime += futs[i].get();
}
System.out.println("使用ThreadLocal包装Random实例:"+ totaltime + "ms");
exe.shutdown();
}
}