老师我的代码如下,我并没有用synchonized,但还是出现了index + wrong count > real index:
package background;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Two thread increment one variable at the same time
*
* @author mixma
*/
public class MultiThreadError implements Runnable {
static MultiThreadError runnableInstance = new MultiThreadError();
private int index = 0;
static AtomicInteger realIndex = new AtomicInteger();
static AtomicInteger wrongCount = new AtomicInteger();
private boolean[] marked = new boolean[100000];
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(runnableInstance);
Thread thread2 = new Thread(runnableInstance);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println("index: " + runnableInstance.index);
System.out.println("real index: " + realIndex);
System.out.println("wrong count: " + wrongCount);
}
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
index++;
realIndex.incrementAndGet();
if (marked[index]) {
System.out.println("Race condition error: " + index);
wrongCount.incrementAndGet();
}
marked[index] = true;
}
}
}
某一次的输出: