Reputation: 61
There are falling snowballs. and when the snowball reaches a certain block (125<=y<=260) that block can only allow one snowball at a time to pass. The problem in my code is, they all pass on that block. It doesn't lock.
What is wrong with my code? Please help.
public void run() {
while(true){
synchronized(this){
if((y>=125)&&(y<=260)){
y+=1;
}
}
if(y>=480){
x = randomGenerator.nextInt(400);
y = 0;
}else{
y=y+1;
}
}
}
Upvotes: 1
Views: 72
Reputation: 311018
If each snowball is its own instance, each one will synchronize on itself (this
), which will be useless. In order to make this piece of code work the way you want, you must have a shared resource all the instances can synchronize on. A good example would be the class object itself:
public void run() {
while(true){
synchronized(Snowball.class){
if((y>=125)&&(y<=260)){
y+=1;
}
}
if(y>=480){
x = randomGenerator.nextInt(400);
y = 0;
}else{
y=y+1;
}
}
}
Upvotes: 3
Reputation: 212
You can use class level synchronization for global locking.
synchronized(YourClassName.class){
// Your code goes here
}
Upvotes: 1