Java Data Type Tutorial - 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 www  . j  a  v a 2s .c  o 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.