Java每日一题系列(4)计算机等级考试

文章作者 100test 发表时间 2010:01:01 12:22:19
来源 100Test.Com百考试题网


  题目:
  请用程序解析ThreadLocal原理,并用程序展示其作用。
  答:
  /**
  *
  */
  package mythread.
  import java.util.Collections.
  import java.util.Map.
  import java.util.HashMap.
  import java.util.Random.
  /**
  * Those code show you muti threads use thread local to keep his own variable or object,
  * and make sure his variable keep the same all the time!
  *
  */
  public class MyThreadLocal {
  /**
  * Main Enter
  * @param args
  */
  public static void main(String[] args) {
  ThreadTest tt=new ThreadTest().
  Thread t1=new Thread(tt,"thread 1").
  Thread t2=new Thread(tt,"thread 2").
  Thread t3=new Thread(tt,"thread 3").
  t1.setPriority(Thread.MAX_PRIORITY).
  t1.start().
  t2.start().
  t3.start().
  }
  }
  /**
  * This thread have use thread local implements MyThreadLocalImpl
  * to keep mutil threads variable, this is a key
  *
  */
  class ThreadTest implements Runnable{
  private static MyThreadLocalImpl threadlocal=new MyThreadLocalImpl().
  @Override
  public void run() {
  String currentThread=Thread.currentThread().getName().
  System.out.println(currentThread " runing").
  VO vo = getVO().
  Random random = new Random().
  int age = random.nextInt(100).
  String value=String.valueOf(age).
  vo.setAge(value).
  System.out.println(currentThread "set age: " vo.getAge()).
  System.out.println(currentThread " first time get age: " vo.getAge()).
  try {
  Thread.sleep(2000).
  } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace().
  }
  System.out.println(currentThread " second get age: " vo.getAge()).
  try {
  Thread.sleep(2000).
  } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace().
  }
  System.out.println(currentThread " third get age: " vo.getAge()).
  //clear up
  clearVO().
  }
  /**
  * Get object from threadlocal
  * @return
  */

相关文章


java面向对象编程笔记:数组的相关事项(14)计算机等级考试
java面向对象编程笔记:多线程的相关事项(13)计算机等级考试
Java每日一题系列(6)计算机等级考试
Java每日一题系列(5)计算机等级考试
Java每日一题系列(4)计算机等级考试
Java每日一题系列(3)计算机等级考试
httpclient抓取网页内容计算机等级考试
HTMLParser学习整理常用的解析代码计算机等级考试
基础编程:Java快速排序实例计算机等级考试
澳大利亚华人论坛
考好网
日本华人论坛
华人移民留学论坛
英国华人论坛