我想测量 2 个线程计数到 1000 需要多长时间。如何对以下代码进行基准测试?
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;
}
}
为什么即使我使用synchronized
关键字我仍然得到以下结果(提取)?
Thread-0 9
Thread-0 11
Thread-0 12
Thread-0 13
Thread-1 10