Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- class MyRunnable implements Runnable {
- private static final ThreadLocal<Integer> thrLoc1 = new ThreadLocal<Integer>() {
- @Override
- protected Integer initialValue() {
- return new Integer(777);
- }
- };
- // same as lambda arg: Supplier<T>, T get()
- private static final ThreadLocal<Integer> thrLoc2 = ThreadLocal.withInitial(() -> 777);
- @Override
- public void run() {
- thrLoc1.set(thrLoc1.get() + 1); // increment Integer (ThreadLocal var)
- System.out.println(thrLoc1.get());
- System.out.println(thrLoc2.get());
- thrLoc2.set(111);
- System.out.println(thrLoc2.get());
- thrLoc1.remove();
- thrLoc2.remove(); // prevents memory leak
- }
- }
- public class Driver {
- public static void main(String[] args) {
- // USING EXECUTOR FRAMEWORK LIKE BELOW NOT RECOMMENDED!
- // USE Thread t = new Thread(Runnable), t.start
- ExecutorService es1 = Executors.newSingleThreadExecutor();
- ExecutorService es2 = Executors.newSingleThreadExecutor();
- Runnable r = new MyRunnable();
- es1.submit(new MyRunnable());
- es2.submit(new MyRunnable());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement