package threaddemo;

public class ThreadLocalDemo {

    public ThreadLocal<Integer> localVar = new ThreadLocal<>();
    private Integer integer = 0;

    public void add() {
        integer = integer + 1;
    }

    public int get() {
        return  integer;
    }

    public static void main(String[] args) {
        ThreadLocalDemo threadLocalDemo = new ThreadLocalDemo();

        threadLocalDemo.localVar.set(threadLocalDemo.integer);

        Thread t1 = new Thread(threadLocalDemo::add, "t1");

        Thread t2 = new Thread( () -> {
            threadLocalDemo.add();
            threadLocalDemo.localVar.set(threadLocalDemo.get());
            System.out.println("value in new thread: " + threadLocalDemo.get());
            System.out.println("value in new thread localVar: " + threadLocalDemo.localVar.get());
        }, "t2");

        t1.start();
        t2.start();

        try {
            t1.join();
            System.out.println("value in main thread: " + threadLocalDemo.get());
            System.out.println("value in main thread localVar: " + threadLocalDemo.localVar.get());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }



}
