Java线程:线程私有变量,java线程私有变量,Java线程:线程私有变
分享于 点击 39717 次 点评:191
Java线程:线程私有变量,java线程私有变量,Java线程:线程私有变
Java线程:线程私有变量
线程对象也是从一个(线程)类而构建的,线程类作为一个类也可以拥有自己的私有成员。这个成员为此线程对象私有,有时候使用线程私有变量,会巧妙避免一些并发安全的问题,提高程序的灵活性和编码的复杂度。
下面举例来说吧,统计一个线程类创建过多少个线程,并为每个线程进行编号。
package cn.outofmemory.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实现的版本,还有其他的,都没有这个代码简洁。
用户点评