Reputation: 71
the Error is:
cannot find symbol
System.out.println("value of count" + count);
Symbol:
variable count
Location:
class synchronize
I declared count
variable static
so doesn't that mean every class can access it?
class a extends Thread
{
public static int count=0;
public void run()
{
for(int i=1;i<=100;i++){
count++;
}
}
}
class b extends Thread {
public void run(){
for(int i=1;i<=100;i++){
count++;
}
}
}
class synchronize {
public static void main(String args[]) {
a obj =new a();
b obj1=new b();
obj.start();
obj1.start();
System.out.println("value of count "+count) ;
}
}
Upvotes: 3
Views: 1807
Reputation: 10995
Since it is public and static, you are correct in that you will be able to access the count
variable in your a
class from anywhere in your code.
However, you cannot access it just by using the variable count
.
Your other classes do not know about any count
variable, but they know about your a
class. So you can use a.count
to access the count
variable in your a
class from any of your other classes.
Upvotes: 2
Reputation: 2316
the count
variable is declared as a member of the a
class.
So if you change:
System.out.println("value of count "+count);
To:
System.out.println("value of count " + a.count);
So that you are accessing the count
variable as a member of the a
class, then your synchornize
class should be able to 'see' the count
variable.
Also, you may want to use the a.count
inside of class b
as well:
class b extends Thread {
public void run(){
for(int i=1;i<=100;i++){
a.count++;
}
}
}
Upvotes: 3
Reputation: 3095
Static variables have a single value for all instances of a class.
You have to access static variables by class name
instead of this
System.out.println("value of count "+count) ;
use this
System.out.println("value of count "+a.count) ;
Upvotes: 2