I'm trying to synchronize my Person
class Methods so that my static counter variable gets decremented by one thread at the a time.
public class Person extends Thread {
private static int count = 10;
public void decrement() {
synchronized(Person.class) {
count--;
}
}
public int getCount() {
return count;
}
public void run(){
while( count > 0){
this.decrement();
System.out.print(this.getCount() + ",");
}
}
}
Here's my main class. Each thread will decrement to static counter via synchronized method to avoid mutiple thread access to same resource.
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Person p1 = new Person();
Person p2 = new Person();
Person p3 = new Person();
Person p4 = new Person();
Person p5 = new Person();
p1.start();
p2.start();
p3.start();
p4.start();
p5.start();
}
}
But when i run my program, it is printing duplicate counter values. What am i doing wrong?
Outputs:
8,8,7,6,5,4,3,2,1,0
8,7,5,3,1,0,6,8,4,0
8,6,4,7,2,8,0,1,3,5
– Aarhus