Created
June 26, 2019 16:46
-
-
Save akshanshjain95/696e8217a798ff65cdba5ffd9babac19 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ThreadConfinementUsingThreadLocal { | |
public static void main(String[] args) { | |
ThreadLocal<String> stringHolder = new ThreadLocal<>(); | |
Runnable runnable1 = () -> { | |
stringHolder.set("Thread in runnable1"); | |
try { | |
Thread.sleep(5000); | |
System.out.println(stringHolder.get()); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
}; | |
Runnable runnable2 = () -> { | |
stringHolder.set("Thread in runnable2"); | |
try { | |
Thread.sleep(2000); | |
stringHolder.set("string in runnable2 changed"); | |
Thread.sleep(2000); | |
System.out.println(stringHolder.get()); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
}; | |
Runnable runnable3 = () -> { | |
stringHolder.set("Thread in runnable3"); | |
try { | |
Thread.sleep(5000); | |
System.out.println(stringHolder.get()); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
}; | |
Thread thread1 = new Thread(runnable1); | |
Thread thread2 = new Thread(runnable2); | |
Thread thread3 = new Thread(runnable3); | |
thread1.start(); | |
thread2.start(); | |
thread3.start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment