线程对象也是从一个(线程)类而构建的,线程类作为一个类也可以拥有自己的私有成员。这个成员为此线程对象私有,有时候使用线程私有变量,会巧妙避免一些并发安全的问题,提高程序的灵活性和编码的复杂度。
下面举例来说吧,统计一个线程类创建过多少个线程,并为每个线程进行编号。
package com.lavasoft.test;
/** * 为线程添加编号,并确所创建过线程的数目 * * @author leizhimin 2010-1-4 14:15:31 */ 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实现的版本,还有其他的,都没有这个代码简洁。
本文转自 leizhimin 51CTO博客,原文链接:http://blog.51cto.com/lavasoft/258380,如需转载请自行联系原作者