Skip to content

Instantly share code, notes, and snippets.

@sbvalijon
Last active January 18, 2019 13:14
Show Gist options
  • Save sbvalijon/39250ae3cda20e4baf872e1602726c2f to your computer and use it in GitHub Desktop.
Save sbvalijon/39250ae3cda20e4baf872e1602726c2f to your computer and use it in GitHub Desktop.
ThreadLocal usage examaple
/**
* It is instantiated only once.
* However can be initialized one or more times per thread.
* The code prints something like this on console:
* field threadLocal has been instantiated!
* Thread with id = 10
* Thread with id = 11
* Thread with id = 12
* */
public class Bar {
public static void main(String[] args) throws InterruptedException {
Foo sharedObject = new Foo();
Thread thread1 = new Thread(sharedObject);
Thread thread2 = new Thread(sharedObject);
Thread thread3 = new Thread(sharedObject);
thread1.start();
thread2.start();
thread3.start();
thread1.join();
thread2.join();
thread3.join();
}
}
class Foo implements Runnable{
private ThreadLocal threadLocal = new ThreadLocal() {
{ System.out.println("field threadLocal has been instantiated!" ); }
};
@Override
public void run() {
threadLocal.set("Thread with id = " + Thread.currentThread().getId());
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(threadLocal.get());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment