为每个线程获取此程序的输出null

时间:2017-05-01 18:28:22

标签: java thread-local

我的输出: - 客户线程 - 1 ....使用客户ID执行:null 客户线程 - 4 ....使用客户ID执行:null 客户线程 - 3 ....使用客户ID执行:null 客户线程 - 2 ....使用客户ID执行:null

请解释为什么在每种情况下都为空。为什么价值不增加enter code here

包裹测试;

class CustomerThread extends Thread {
    static Integer custId = 0;

    private static ThreadLocal tl = new ThreadLocal() {
        protected Integer intialValue() {
            return ++custId; //This ++custId is not incrementing
        }
    };

    CustomerThread(String name) {
        super(name);
    }

    public void run() {
        System.out.println(Thread.currentThread().getName() + "....executing with customer id :" + tl.get());?// tl.get() is not getting the values
    }
}

class Test {
    public static void main(String[] args) {
        CustomerThread c1 = new CustomerThread("Customer Thread - 1");
        CustomerThread c2 = new CustomerThread("Customer Thread - 2");
        CustomerThread c3 = new CustomerThread("Customer Thread - 3");
        CustomerThread c4 = new CustomerThread("Customer Thread - 4");
        c1.start();
        c2.start();
        c3.start();
        c4.start();
    }
}

1 个答案:

答案 0 :(得分:1)

您需要实际设置()和get()以与ThreadLocal变量进行交互:

class CustomerThread extends Thread {
    private static int customerID = 0;

    private static ThreadLocal tl = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return ++customerID;
        }
    };

    CustomerThread(String name) {
        super(name);
    }

    public void run() {
        tl.set(tl.get());
        System.out.println(Thread.currentThread().getName() + "....executing with customer id :" + tl.get());
    }
}

输出:

Customer Thread - 1....executing with customer id :1
Customer Thread - 3....executing with customer id :3
Customer Thread - 4....executing with customer id :4
Customer Thread - 2....executing with customer id :2