I want to measure how long it takes for the 2 threads to count till 1000. How can I make a benchmark test of the following code?
public class Main extends Thread {
public static int number = 0;
public static void main(String[] args) {
Thread t1 = new Main();
Thread t2 = new Main();
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
for (int i = 0; i <= 1000; i++) {
increment();
System.out.println(this.getName() + " " + getNumber());
}
}
public synchronized void increment() {
number++;
}
public synchronized int getNumber() {
return number;
}
}
And why am I still getting the following result (extract) even though I use the synchronized keyword?
Thread-0 9
Thread-0 11
Thread-0 12
Thread-0 13
Thread-1 10
You are not synchronized. The
synchronizedkeyword is an equivalent tosynchonize (this) {}but you are increasing astaticnumber which is not contained within your object. You actually have 2 objects/threads and both of them synchronize with themself, not with each other.Either make you property
volatileand don’t synchronize at all or use a lock Object like this: