一个带有同步的简单多线程测试。我以为如果它被“同步”,其他线程会等待。我错了吗?
我认为这应该显示类似以下内容的东西:
但实际输出为:
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)显示,但不是按顺序...
static
(与synchronized
结合使用)是否足够保证它的线程安全,还是应该将变量声明为volatile
? - Clockwork-Musevolatile
所添加的全部内容。 - Sean Owen