我有一个“计数器”类,它增加一个计数器直到一个限制。我创建了这个类的 N 个实例,每个类都会增加计数器,直到 MAX_COUNT/N。我已经实现了同步方法,但计数器从未达到 MAX_COUNT 值(我将发布代码,这将有助于理解问题)
主.java
package monitores;
// MAIN PROGRAM, IT CREATES THE THREADS, RUNS THEM AND JOINS, AT THE END
// DISPLAYS THE COUNTER VALUE
public class Main {
public static void main(String[] args) throws InterruptedException {
Hilo hilos[] = new Hilo[Hilo.NUM_THREADS];
for(int i = 0; i < Hilo.NUM_THREADS; i++){
hilos[i] = new Hilo();
hilos[i].start();
}
for(int i = 0; i < Hilo.NUM_THREADS; i++){
hilos[i].join();
}
System.out.println("Counter value at the end: "+Hilo.count());
}
}
希洛.java
package monitores;
public class Hilo extends Thread {
public static final int MAX_COUNT = 40000;
public static final int NUM_THREADS = 4;
private static volatile int count = 0;
public static int count() {
return count;
}
@Override
public void run() {
int max = MAX_COUNT / NUM_THREADS;
for (int i = 0; i < max; i++) {
synchronized(this){
count++;
}
}
}
}
如果我运行 Main.java,结果如下:
Counter value at the end: 33870
这是一个随机数,但总是接近 MAX_COUNT。
先感谢您。