Monday, September 3, 2012

Thread Local Example

A simple example for Thread Local concept in Java:

public
class ThreadLocalExamples {
public static int x =0;
private static ThreadLocal<Integer> tlocal;
public static void main(String[] args) {
tlocal = new ThreadLocal<Integer>();
ThreadLocalExamples tl =
new ThreadLocalExamples();
T1 t1 = tl.
new T1();
t1.start();
T2 t2 = tl.
new T2();
t2.start();
tlocal.set(100);
System.
out.println("main thread->"+tlocal.get());
try {
t1.join();
t2.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.
out.println(x);
}
class T1 extends Thread {
@Override
public void run() {
x++;
System.
out.println("value in t1->"+tlocal.get());
tlocal.set(200);
System.
out.println("value in t1->"+tlocal.get());
}
}
class T2 extends Thread {
@Override
public void run() {
x++;
System.
out.println("value in t2->"+ tlocal.get());
tlocal.set(300);
}
}
}

 Output:
main thread->100
value in t1->null
value in t1->200
value in t2->null
2

No comments:

Post a Comment