File tree 1 file changed +49
-0
lines changed
RandomProblems/src/sporadic/thread
1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ package sporadic .thread ;
2
+
3
+ /**
4
+ * The ThreadLocal class in Java enables you to create variables that can only
5
+ * be read and written by the same thread. Thus, even if two threads are
6
+ * executing the same code, and the code has a reference to a ThreadLocal
7
+ * variable, then the two threads cannot see each other's ThreadLocal variables.
8
+ *
9
+ * Since values set on a ThreadLocal object only are visible to the thread who
10
+ * set the value, no thread can set an initial value on a ThreadLocal using
11
+ * set() which is visible to all threads.
12
+ * Instead you can specify an initial value for a ThreadLocal object by
13
+ * subclassing ThreadLocal and overriding the initialValue() method. Here is how
14
+ * that looks:
15
+ *
16
+ * private ThreadLocal myThreadLocal = new ThreadLocal<String>() {
17
+ * @Override
18
+ * protected String initialValue() { return "This is the initial value"; }
19
+ * };
20
+ */
21
+
22
+ public class ThreadLocalExample {
23
+
24
+ public static class MyRunnable implements Runnable {
25
+
26
+ private ThreadLocal <Integer > threadLocal = new ThreadLocal <Integer >();
27
+
28
+ @ Override
29
+ public void run () {
30
+ threadLocal .set ((int ) (Math .random () * 100D ));
31
+ try {
32
+ Thread .sleep (2000 );
33
+ } catch (InterruptedException e ) {
34
+ e .printStackTrace ();
35
+ }
36
+ System .out .println ("threadLocal.get() is: " + threadLocal .get ());
37
+ }
38
+
39
+ public static void main (String ... args ) {
40
+ MyRunnable sharedRunnableInstance = new MyRunnable ();
41
+ Thread t1 = new Thread (sharedRunnableInstance );
42
+ Thread t2 = new Thread (sharedRunnableInstance );
43
+
44
+ t1 .start ();
45
+ t2 .start ();
46
+ }
47
+ }
48
+
49
+ }
You can’t perform that action at this time.
0 commit comments