Thread local in java
Thread Local
public class Threadlocal {
public static class MyRunnable implements Runnable {
private int id;
public MyRunnable(int id) {
// TODO Auto-generated constructor stub
this.id = id;
}
private ThreadLocal threadLocal = new ThreadLocal();
@Override
public void run() {
threadLocal.set(id);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println(threadLocal.get());
}
}
public static void main(String[] args) throws InterruptedException {
MyRunnable sharedRunnableInstance = new MyRunnable(23);
MyRunnable sharedRunnableInstance1 = new MyRunnable(34);
Thread thread1 = new Thread(sharedRunnableInstance);
Thread thread2 = new Thread(sharedRunnableInstance1);
thread1.start();
thread2.start();
thread1.join(); // wait for thread 1 to terminate
thread2.join(); // wait for thread 2 to terminate
}
}
Comments
Post a Comment