线程对象也是从一个(线程)类而构建的,线程类作为一个类也可以拥有自己的私有成员。这个成员为此线程对象私有,有时候使用线程私有变量,会巧妙避免一些并发安全的问题,提高程序的灵活性和编码的复杂度。
下面举例来说吧,统计一个线程类创建过多少个线程,并为每个线程进行编号。
/**
* 为线程添加编号,并确所创建过线程的数目
*
* @author SWPU 2019-12-24 16:38: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