-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathThreadLocalDemo.java
63 lines (52 loc) · 2 KB
/
ThreadLocalDemo.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
import java.util.concurrent.ThreadLocalRandom;
/**
* In this example, 3 threads will print the 3 consecutive exponential values of 1, 2 and 3.
* All of them will be using the SharedUtil class for it.
* P.S. SharedUtil uses Java ThreadLocal class which enables us to create variables that can only be read and written by the same thread.
*/
public class ThreadLocalDemo {
public static void main(String[] args) {
new ThreadLocalDemo().execute();
}
private void execute() {
for (int i = 1; i <= 3; i++) {
new Thread(new Task(i), "Thread exp" + i).start();
}
}
private static class Task implements Runnable {
private final int num;
private Task(int num) {
this.num = num;
}
@Override
public void run() {
try {
SharedUtil.setCounter(num);
for (int i = 0; i < 3; i++) {
SharedUtil.calculateAndPrint();
Thread.sleep(ThreadLocalRandom.current().nextInt(100, 500));
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
SharedUtil.remove();
}
}
}
private static class SharedUtil {
private static final ThreadLocal<Integer> threadLocalCounter = ThreadLocal.withInitial(() -> 0);
private static final ThreadLocal<Integer> threadLocalAccumulator = ThreadLocal.withInitial(() -> 0);
static void setCounter(int number) {
threadLocalCounter.set(number);
threadLocalAccumulator.set(number);
}
static void calculateAndPrint() {
System.out.println(Thread.currentThread().getName() + ": " + threadLocalAccumulator.get());
threadLocalAccumulator.set(threadLocalAccumulator.get() * threadLocalCounter.get());
}
static void remove() {
threadLocalAccumulator.remove();
threadLocalCounter.remove();
}
}
}