在多线程使用之ThreadLocal

public class Test {

    public static ThreadLocal<Integer> local = new ThreadLocal<Integer>();
    public static ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());


    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            service.execute(new Runnable() {
                @Override
                public void run() {
                    if (Test.local.get() == null) {
                        Test.local.set(1);
                    } else {
                        Test.local.set(Test.local.get() + 1);
                    }
                    System.out.println(Thread.currentThread().getName() + " " + Test.local.get());
                }
            });
        }
        service.shutdown();
    }
}

执行后的结果,看见执行后线程中的变量是更新了,但是在一个线程处理多个任务时候不能使用。
pool-1-thread-2 1
pool-1-thread-2 2
pool-1-thread-3 1
pool-1-thread-3 2
pool-1-thread-3 3
pool-1-thread-3 4
pool-1-thread-3 5
pool-1-thread-3 6
pool-1-thread-3 7
pool-1-thread-3 8
pool-1-thread-3 9
pool-1-thread-3 10
pool-1-thread-3 11
pool-1-thread-3 12
pool-1-thread-3 13
pool-1-thread-3 14
pool-1-thread-3 15
pool-1-thread-2 3
pool-1-thread-1 1
pool-1-thread-4 1

猜你喜欢

转载自janle.iteye.com/blog/2351227