我有一个Java程序,其中有一个偶数对象,有一个下一个方法,该方法将一个值递增两次:
public class Even
{
private int n = 0;
public int next()
{
n++;
n++;
return n;
}
}
如果我从main方法运行两个线程,并在其中访问同一个对象,则它总是返回偶数。由于两个线程都访问相同的对象,因此它是否应该在某个时候不返回不均匀的值?
Even even = new Even();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
System.out.println(even.next());
if (i % 2 == 0) {
try {
System.out.println("even");
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println("fail");
Logger.getLogger(Exercise2.class.getName()).log(Level.SEVERE, null, ex);
return;
}
}
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
System.out.println(even.next());
if (i % 2 == 0) {
try {
System.out.println("even");
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println("fail");
Logger.getLogger(Exercise2.class.getName()).log(Level.SEVERE, null, ex);
return;
}
}
}
});
t1.start();
t2.start();
}
}
有人可以澄清我的困惑吗?