Skip to content

Instantly share code, notes, and snippets.

@sbvalijon
Last active January 10, 2019 05:16
Show Gist options
  • Save sbvalijon/643fc390771970beead2ee18400a5b14 to your computer and use it in GitHub Desktop.
Save sbvalijon/643fc390771970beead2ee18400a5b14 to your computer and use it in GitHub Desktop.
public class ThreadLocalExample {
public static class MyRunnable implements Runnable {
private ThreadLocal<Integer> threadLocal =
new ThreadLocal<Integer>();
@Override
public void run() {
threadLocal.set( (int) (Math.random() * 100D) );
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println(threadLocal.get());
}
}
public static void main(String[] args) {
MyRunnable sharedRunnableInstance = new MyRunnable();
Thread thread1 = new Thread(sharedRunnableInstance);
Thread thread2 = new Thread(sharedRunnableInstance);
thread1.start();
thread2.start();
thread1.join(); //thread 1 tugashini kutish
thread2.join(); //thread 2 tugashini kutish
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment