package demo5;
class Process extends Thread {
static int counter = 0;
public static synchronized void increment() { counter++; }
public void run() {
for (int i = 0; i < 1000000; i++)
{
increment();
}
System.out.println("Done.");
}
}
public class App {
public static void main(String[] args) throws InterruptedException {
Process p1 = new Process();
Process p2 = new Process();
p1.start();
p2.start();
p1.join();
p2.join();
System.out.println("Value of count is :" + p1.counter);
}
}
インクリメント関数を非静的関数として宣言すると、最後のカウンターの値は 200 万にはなりません。
一方、increment メソッドが static として定義されている場合は適切に機能します。
私の知る限り、すべての Process オブジェクトに対してインクリメント関数は 1 つしかありません..では、なぜそれを静的メソッドとして宣言する必要があるのでしょうか..?
ありがとう