下面代码是网上找来的缓存行对齐的demo,网上说前后补7个long类型可以提交效率. 但是我本地运行效率是一模一样的 , 求助一下大神你们运行如何?另外缓存行对齐 不是必须加上关键字volatile才能成功通知其他线程吗? 如果这种代码能提高效率 是不是说明cpu底层做了缓存一致性 那么volatile的线程可见性不就不成立了吗?
public class Test15Demo {
private static class T{
// private long l1, l2, l3, l4, l5, l6, l7;
public long x = 0L;
// private long l8, l9, l10, l11, l12, l13, l14;
}
public static T[] arr = new T[2];
static {
arr[0] = new T();
arr[1] = new T();
}
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(2);
Thread t1 = new Thread(() -> {
for (int l = 0; l < 10_0000_0000L; l++) {
arr[0].x = l;
}
countDownLatch.countDown();
});
Thread t2 = new Thread(() -> {
for (int l = 0; l < 10_0000_0000L; l++) {
arr[1].x = l;
}
countDownLatch.countDown();
});
final long start = System.currentTimeMillis();
t1.start();
t2.start();
countDownLatch.await();
System.out.println(System.currentTimeMillis() - start);
}
}