JAVA多线程之ThreadLocal

ThreadLocal提供线程局部变量,即为使用相同变量的每一个线程维护一个该变量的副本。当某些数据是以线程为作用域并且不同线程具有不同数据副本的时候就可以采用ThreadLocal。

常用方法:

  • initialValue()
  • set()
  • get()

示例代码:

模拟多线程情况下转账操作

package threadcontrol;

public class ThreadLocalDemo {
    private static class Bank{
        private ThreadLocalthreadLocal = new ThreadLocal(){
            @Override
            protected Integer initialValue(){
                return 0;
            }
        };
        public Integer get(){
            return threadLocal.get();
        }
        public void set(Integer money){
            threadLocal.set(threadLocal.get()+money);
        }
    }
    private static class Transfer implements Runnable{
        private Bank bank;
        public Transfer(Bank bank){
            this.bank = bank;
        }

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                bank.set(10);
                System.out.println(Thread.currentThread().getName()+" 转账结果:"+bank.get());
            }
        }
    }

    public static void main(String[] args) {
        Bank bank = new Bank();
        Transfer transfer = new Transfer(bank);
        Thread thread1 = new Thread(transfer,"客户1");
        Thread thread2 = new Thread(transfer,"客户2");
        thread1.start();
        thread2.start();

    }
}

运行结果:

线程操作对应的本地变量,互不干扰

JAVA多线程之ThreadLocal_第1张图片

你可能感兴趣的:(java,java,多线程,ThreadLocal)