Java 从静态方法访问非静态变量计数?
如何从这里的静态main方法访问非静态变量计数。我原以为会出错。编译器应该抛出一个错误。如果我错了,请纠正我 无法从静态上下文访问非静态成员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
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是未定义的行为。