一个简单的带同步的多线程测试。我想如果它是“同步的”,其他线程会等待。我错过了什么?
public class MultithreadingCounter implements Runnable {
static int count = 0;
public static void main(String[] args) {
int numThreads = 4;
Thread[] threads = new Thread[numThreads];
for (int i = 0; i < numThreads; i++)
threads[i] = new Thread(new MultithreadingCounter(), i + "");
for (int i = 0; i < numThreads; i++)
threads[i].start();
for (int i = 0; i < numThreads; i++)
try {
threads[i].join();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
increment();
}
public synchronized void increment(){
System.out.print(Thread.currentThread().getName() + ": " + count + "\t");
count++; // if I put this first or increment it directly in the print line, it works fine.
}
}
我认为这会显示如下内容:
0: 1 2: 0 1: 2 3: 3
但它的实际输出:
0: 0 2: 0 1: 0 3: 3
和其他类似的变化。它应该不按顺序显示每个增量(即 0,1,2,3)...