下面的代码在线程中增加一个静态变量,并检查它的值是否增加了 1。这是Assert.assertEquals(currentAVal+1, accessCounter);
检查。
测试始终通过 10'000 次运行。但是为什么没有竞争条件导致测试失败?我希望在断言发生之前有两个或更多线程accessCounter
在行增加,accessCounter = accessCounter + 1;
但这似乎没有发生?
public class RunnableTest {
private static int accessCounter = 0;
private class Post implements Runnable {
public void run() {
int currentAVal = accessCounter;
accessCounter = accessCounter + 1;
Assert.assertEquals(currentAVal+1, accessCounter);
System.out.println("Access counter : "+accessCounter);
}
}
@Test
public void runTest(){
Runnable r = new Post();
ScheduledExecutorService executor = Executors.newScheduledThreadPool(4);
for(int executorCount = 0; executorCount < 10000; ++executorCount) {
executor.execute(r);
}
}
}
更新:从 Gray 的回答中,我更新了代码,当我删除 println 语句时,我现在收到一个竞争条件(测试失败):
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import junit.framework.Assert;
public class RunnableTest {
private static int accessCounter = 0;
private static List<String> li = new ArrayList<String>();
private class Post implements Runnable {
public synchronized void run() {
int currentAVal = accessCounter;
accessCounter = accessCounter + 1;
li.add(String.valueOf(currentAVal+1+","+accessCounter));
}
}
@Test
public void runTest(){
Runnable r = new Post();
ScheduledExecutorService executor = Executors.newScheduledThreadPool(4);
for(int executorCount = 0; executorCount < 10000; ++executorCount) {
executor.execute(r);
}
//Wait for threads to finish
// we shut it down once we've submitted all jobs to it
executor.shutdown();
// now we wait for all of those jobs to finish
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
for(String s : li){
Assert.assertEquals(s.split(",")[0], s.split(",")[1]);
}
}
}
添加synchronized
到 run 方法会导致测试通过