Java ThreadLocal.initialValue()

Syntax

ThreadLocal.initialValue() has the following syntax.

protected T initialValue()

Example

In the following code shows how to use ThreadLocal.initialValue() method.


public class Main {
  public static void main(String[] args) {
//from   w ww  .ja  v a2  s  . co m
    MyThread t1 = new MyThread("R");
    MyThread t2 = new MyThread("S");

    // this will call run() method
    t1.start();
    t2.start();
  }
}
class MyThreadLocal extends ThreadLocal {
  private static int n = 10;
  protected Object initialValue() {
    return new Integer(n--);
  }
}



class MyThread extends Thread {
  ThreadLocal t = new MyThreadLocal();

  MyThread(String name) {
    super(name);
  }
  
  public void run() {
    for (int i = 0; i < 2; i++)
      System.out.println(getName() + " " + t.get());
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    java.lang »




Boolean
Byte
Character
Class
Double
Enum
Float
Integer
Long
Math
Number
Object
Package
Process
ProcessBuilder
Runnable
Runtime
SecurityManager
Short
StackTraceElement
StrictMath
String
StringBuffer
StringBuilder
System
Thread
ThreadGroup
ThreadLocal
Throwable