Java并发 专题
您的位置:java > Java并发专题 > Java并发ThreadLocal类
Java并发ThreadLocal类
作者:--    发布时间:2019-11-20

threadlocal类用于创建只能由同一个线程读取和写入的线程局部变量。 例如,如果两个线程正在访问引用相同threadlocal变量的代码,那么每个线程都不会看到任何其他线程操作完成的线程变量。

线程方法

以下是threadlocal类中可用的重要方法的列表。

编号 方法 描述
1 public t get() 返回当前线程的线程局部变量的副本中的值。
2 protected t initialvalue() 返回此线程局部变量的当前线程的“初始值”。
3 public void remove() 删除此线程局部变量的当前线程的值。
4 public void set(t value) 将当前线程的线程局部变量的副本设置为指定的值。

实例

以下testthread程序演示了threadlocal类的上面一些方法。 这里我们使用了两个计数器(counter)变量,一个是常量变量,另一个是threadlocal变量。

class runnabledemo implements runnable {
   int counter;
   threadlocal<integer> threadlocalcounter = new threadlocal<integer>();

   public void run() {     
      counter++;
      if(threadlocalcounter.get() != null){
         threadlocalcounter.set(threadlocalcounter.get().intvalue() + 1);
      }else{
         threadlocalcounter.set(0);
      }
      system.out.println("counter: " + counter);
      system.out.println("threadlocalcounter: " + threadlocalcounter.get());
   }
}

public class testthread {

   public static void main(string args[]) {
      runnabledemo commoninstance = new runnabledemo();

      thread t1 = new thread( commoninstance);
      thread t2 = new thread( commoninstance);
      thread t3 = new thread( commoninstance);
      thread t4 = new thread( commoninstance);

      t1.start();
      t2.start();
      t3.start();
      t4.start();

      // wait for threads to end
      try {
         t1.join();
         t2.join();
         t3.join();
         t4.join();
      }catch( exception e) {
         system.out.println("interrupted");
      }
   }
}

这将产生以下结果 -

counter: 1
threadlocalcounter: 0
counter: 2
threadlocalcounter: 0
counter: 4
counter: 3
threadlocalcounter: 0
threadlocalcounter: 0

您可以看到变量(counter)的值由每个线程增加,但是threadlocalcounter对于每个线程都保持为0


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册