|
| 1 | +packagesporadic.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 | +publicclassThreadLocalExample { |
| 23 | + |
| 24 | +publicstaticclassMyRunnableimplementsRunnable { |
| 25 | + |
| 26 | +privateThreadLocal<Integer>threadLocal =newThreadLocal<Integer>(); |
| 27 | + |
| 28 | +@Override |
| 29 | +publicvoidrun() { |
| 30 | +threadLocal.set((int) (Math.random() *100D)); |
| 31 | +try { |
| 32 | +Thread.sleep(2000); |
| 33 | +}catch (InterruptedExceptione) { |
| 34 | +e.printStackTrace(); |
| 35 | +} |
| 36 | +System.out.println("threadLocal.get() is: " +threadLocal.get()); |
| 37 | +} |
| 38 | + |
| 39 | +publicstaticvoidmain(String...args) { |
| 40 | +MyRunnablesharedRunnableInstance =newMyRunnable(); |
| 41 | +Threadt1 =newThread(sharedRunnableInstance); |
| 42 | +Threadt2 =newThread(sharedRunnableInstance); |
| 43 | + |
| 44 | +t1.start(); |
| 45 | +t2.start(); |
| 46 | +} |
| 47 | +} |
| 48 | + |
| 49 | +} |