专注Java教育14年 全国咨询/投诉热线:444-1124-454
星辉LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 Java私有变量简介

Java私有变量简介

更新时间:2022-08-25 10:34:14 来源:星辉 浏览1223次

线程对象也是线程类创建的,也有私有成员。这个私有成员,是线程私有的。有时候使用线程私有变量,会巧妙避免一些并发安全的问题,提高程序的灵活性和编码的复杂度。

/** 
* 为线程添加编号,确定创建过线程的数目 
* 
*/ 
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;    //线程数 
        private int x = 0;               //线程编号 
        MyThread() { 
                x = n++; 
        } 
        @Override 
        public void run() { 
                Thread t = Thread.currentThread(); 
                System.out.println(t.getName() + "\t" + x); 
        } 
}

 

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>