我编写了一个多线程和同步递增函数,但它没有显示一致的输出:-
$ java Main
count: 999883
$ java Main
count: 1000000
$ java Main
count: 999826
$ java Main
count: 1000000
$ java Main
count: 1000000
我有一个同步计数器:-
public class Counter {
public int count;
synchronized void inc() {
count = count+1;
}
int getCount() {
return count;
}
}
使用计数器对象初始化并将其递增 1000 次的线程类:-
public class CountPrimesRunnable implements Runnable {
private Counter c;
public CountPrimesRunnable(Counter c) {
this.c = c;
}
public void run() {
for (int i = 0; i < 1000; i++)
c.inc();
}
}
以及一次创建 1000 个线程的 Main 类:-
public class Main {
public static void main(String[] args) {
int numberOfThreads = 1000;
Thread[] worker = new Thread[numberOfThreads];
Counter c = new Counter();
for (int i = 0; i < numberOfThreads; i++)
worker[i] = new Thread(new CountPrimesRunnable(c));
for (int i = 0; i < numberOfThreads; i++)
worker[i].start();
System.out.println("count: " + c.count);
}
}
我错过了什么?