threadlocalexample.java

来自「java 完全探索的随书源码」· Java 代码 · 共 37 行

JAVA
37
字号
public class ThreadLocalExample extends Thread{  // Static instance for all threads to use  private static MyThreadLocal theadLocal = new MyThreadLocal();  // Holds which thread number this instance is. Used for display only  private int threadCount = 0;  // Default Constructor  public ThreadLocalExample( String threadName, int threadCount )  {    super( threadName );    this.threadCount = threadCount;  }  // Use a inner class to declare our new class  static private class MyThreadLocal extends ThreadLocal  {    // If this is the first time the get or set is used,    // this method will be called automatically    protected Object initialValue()    {      // Initialize a new Double object      return new Double (Math.random() * 1000.0);    }  }  // Override the parents run method  public void run()  {    // Print out the initial value for the ThreadLocal Object    System.out.println( getName() + " - Initial Value: " + this.theadLocal.get() );    // Change the value for this thread only    this.theadLocal.set( new Integer( threadCount ) );    // Print out the value, so that we can be sure that only our instance changed    System.out.println( getName() + " - Current Value: " + this.theadLocal.get() );  }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?