首页 课程 师资 教程 报名

Java私有变量简介

  • 2022-08-25 10:34:14
  • 1214次 动力节点

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

/** 
* 为线程添加编号,确定创建过线程的数目 
* 
*/ 
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() + "	" + x); 
        } 
}

 

选你想看

你适合学Java吗?4大专业测评方法

代码逻辑 吸收能力 技术学习能力 综合素质

先测评确定适合在学习

在线申请免费测试名额
价值1998元实验班免费学
姓名
手机
提交