Java线程:线程私有变量
来源:优易学  2010-1-15 14:42:36   【优易学:中国教育考试门户网】   资料下载   IT书店

  线程对象也是从一个(线程)类而构建的,线程类作为一个类也可以拥有自己的私有成员。这个成员为此线程对象私有,有时候使用线程私有变量,会巧妙避免一些并发安全的问题,提高程序的灵活性和编码的复杂度。

  下面举例来说吧,统计一个线程类创建过多少个线程,并为每个线程进行编号。

  package com.lavasoft.test;

  /**

  * 为线程添加编号,并确所创建过线程的数目

  */

  public class ThreadVarTest {

  public static void main(String[] args) {

  Thread t1 = new MyThread();

  Thread t2 = new MyThread();

  Thread t3 = new MyThread();

  Thread t4 = new MyThread();

  t1.start();

  t2.start();

  t3.start();

  t4.start();

  }

  }

  class MyThread extends Thread {

  private static int sn = 0;    //线程数

  private int x = 0;                    //线程编号

  MyThread() {

  x = sn++;

  }

  @Override

  public void run() {

  Thread t = Thread.currentThread();

  System.out.println(t.getName() + "\t" + x);

  }

  }

  运行结果:

  Thread-0  0

  Thread-1  1

  Thread-2  2

  Thread-3  3

  Process finished with exit code 0

  这个程序是很多公司面试题,这是一种求解方式,应该是最简单的求解方式。还有用ThreadLocal实现的版本,还有其他的,都没有这个代码简洁。

责任编辑:cyth

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