Java线程:深入ThreadLocal
来源:优易学  2010-1-15 14:43:02   【优易学:中国教育考试门户网】   资料下载   IT书店

 

  二、不用ThreadLocal

  假如不用ThreadLocal,只需要将MyThreadLocal类重新定义为:

  /**

  * 使用了ThreadLocal的类

  *

  */

  public class MyThreadLocal {

  private Integer t1 = 0;

  public Integer getNextNum(){

  return t1=t1+1;

  }

  //        //定义了一个ThreadLocal变量,用来保存int或Integer数据

  //        private ThreadLocal<Integer> tl = new ThreadLocal<Integer>() {

  //                @Override

  //                protected Integer initialValue() {

  //                        return 0;

  //                }

  //        };

  //

  //        public Integer getNextNum() {

  //                //将tl的值获取后加1,并更新设置t1的值

  //                tl.set(tl.get() + 1);

  //                return tl.get();

  //        }

  }

  然后运行测试:

  Thread-2  1

  Thread-2  2

  Thread-1  4

  Thread-1  6

  Thread-3  3

  Thread-3  9

  Thread-3  10

  Thread-1  8

  Thread-0  7

  Thread-0  11

  Thread-0  12

  Thread-2  5

  Process finished with exit code 0

  从这里可以看出,四个线程共享了tlt变量,结果每个线程都直接修改tlt的属性。

上一页  [1] [2] [3] [4] 下一页

责任编辑:cyth

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训