-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThreadLocalsMain.java
48 lines (36 loc) · 1.15 KB
/
ThreadLocalsMain.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
package example2;
import java.util.Random;
public class ThreadLocalsMain {
static Random rnd = new Random();
static synchronized int generateRandom() {
return rnd.nextInt();
}
static final ThreadLocal<Integer> someInt = new ThreadLocal<Integer>() {
@Override
protected Integer initialValue() {
return generateRandom();
}
};
static Thread createConsumer(final String name) {
return new Thread(new Runnable() {
public void run() {
int initialValue = someInt.get();
int test = someInt.get();
assert(test == initialValue);
System.out.println(
String.format("Value returned by %s: %d", name, initialValue)
);
}
});
}
public static void main(String[] args) throws InterruptedException {
Thread th1 = createConsumer("Thread 1");
Thread th2 = createConsumer("Thread 2");
th1.start();
th2.start();
th1.join();
th2.join();
System.out.println(
"Value read by main: " + someInt.get());
}
}