更新時間:2022-08-25 10:34:14 來源:動力節(jié)點 瀏覽1811次
線程對象也是線程類創(chuàng)建的,也有私有成員。這個私有成員,是線程私有的。有時候使用線程私有變量,會巧妙避免一些并發(fā)安全的問題,提高程序的靈活性和編碼的復(fù)雜度。
/**
* 為線程添加編號,確定創(chuàng)建過線程的數(shù)目
*
*/
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 n = 0; //線程數(shù)
private int x = 0; //線程編號
MyThread() {
x = n++;
}
@Override
public void run() {
Thread t = Thread.currentThread();
System.out.println(t.getName() + "\t" + x);
}
}
初級 202925
初級 203221
初級 202629
初級 203743