Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从静态方法访问非静态变量计数?_Java - Fatal编程技术网

Java 从静态方法访问非静态变量计数?

Java 从静态方法访问非静态变量计数?,java,Java,如何从这里的静态main方法访问非静态变量计数。我原以为会出错。编译器应该抛出一个错误。如果我错了,请纠正我 无法从静态上下文访问非静态成员 class sync { private int count; public static void main (String args[]) { sync obj =new sync(); obj.do(); } public void do() { Thread t =new Thread(new Run

如何从这里的静态main方法访问非静态变量计数。我原以为会出错。编译器应该抛出一个错误。如果我错了,请纠正我 无法从静态上下文访问非静态成员

class sync {

  private int count;
  public static void main (String args[]) {

    sync obj =new sync();
    obj.do();
  }

  public void do() {

    Thread t =new Thread(new Runnable () {

      public void run() {
        for(int i=0;i<=1000;i++) {
          count++;
        }
      }
    });

    Thread t1=new Thread (new Runnable () {

      public void run () {
        for(int i=0;i<=1000;i++) {
          count++;
        }
      }
    });

    t.start();
    t1.start();
    System.out.println(count) ;
  }
}
类同步{
私人整数计数;
公共静态void main(字符串参数[]){
sync obj=新同步();
obj.do();
}
公营部门{
线程t=新线程(新可运行(){
公开募捐{

对于(inti=0;i它在静态方法中不被访问

在被访问的地方,它不是在静态上下文中访问的,而是通过同步实例访问的

public static void main(String[] a){
  int a = count; // this would be wrong, and cause the error you expect
}

public static void main(String[] a){
  sync a = new sync();
  int b = a.getCount(); // or even a.count; for a public variable
  // is valid, since even though it is within a static method, it is not in 
  // a static context
}

static
方法访问
count
在哪里?
do
不是
static
…作为旁白;在Java中,我们总是对类使用
PascalCase
Sync
是一个类,
Sync
不是。因为
count
不受锁保护,也不是
volatile
,所以代码的lt是未定义的行为。