我最近参加了一次采访,其中有一个问题被问到“是否可以改进以下代码”:
public class Performance{
static class C1 {
volatile long c1;
volatile long c2;
}
static C1 p = new C1();
static class Worker implements Runnable {
private static final int INT = Integer.MAX_VALUE / 8;
private final boolean b;
Worker(boolean b) {
this.b = b;
}
@Override
public void run() {
if (b) {
for (int i = 0; i < INT; i++) {
p.c1++;
}
} else {
for (int i = 0; i < INT; i++) {
p.c2++;
}
}
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new Worker(true));
Thread t2 = new Thread(new Worker(false));
t1.start();
t2.start();
}
}