Skip to content

Commit 860d444

Browse files
authored
Add files via upload
1 parent 3ff811d commit 860d444

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

ThreadLocalDemo.java

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package thread;
2+
3+
import java.util.concurrent.ThreadLocalRandom;
4+
5+
/**
6+
* In this example, 3 threads will print the 3 consecutive exponential values of 1, 2 and 3.
7+
* All of them will be using the SharedUtil class for it.
8+
* P.S. SharedUtil uses Java ThreadLocal class which enables us to create variables that can only be read and written by the same thread.
9+
*/
10+
public class ThreadLocalDemo {
11+
12+
public static void main(String[] args) {
13+
14+
new ThreadLocalDemo().execute();
15+
16+
}
17+
18+
private void execute() {
19+
for (int i = 1; i <= 3; i++) {
20+
new Thread(new Task(i), "Thread exp" + i).start();
21+
}
22+
}
23+
24+
private class Task implements Runnable {
25+
26+
private int num;
27+
28+
Task(int num) {
29+
this.num = num;
30+
}
31+
32+
@Override
33+
public void run() {
34+
try {
35+
SharedUtil.setCounter(num);
36+
37+
for (int i = 0; i < 3; i++) {
38+
SharedUtil.calculateAndPrint();
39+
Thread.sleep(ThreadLocalRandom.current().nextInt(100, 500));
40+
}
41+
} catch (InterruptedException e) {
42+
e.printStackTrace();
43+
} finally {
44+
SharedUtil.remove();
45+
}
46+
}
47+
}
48+
49+
private static class SharedUtil {
50+
private static ThreadLocal<Integer> threadLocalCounter = ThreadLocal.withInitial(() -> 0);
51+
private static ThreadLocal<Integer> threadLocalAccumulator = ThreadLocal.withInitial(() -> 0);
52+
53+
static void setCounter(int number) {
54+
threadLocalCounter.set(number);
55+
threadLocalAccumulator.set(number);
56+
}
57+
58+
static void calculateAndPrint() {
59+
System.out.println(Thread.currentThread().getName() + ": " + threadLocalAccumulator.get());
60+
threadLocalAccumulator.set(threadLocalAccumulator.get() * threadLocalCounter.get());
61+
}
62+
63+
static void remove() {
64+
threadLocalAccumulator.remove();
65+
threadLocalCounter.remove();
66+
}
67+
}
68+
}

0 commit comments

Comments
 (0)