67,514
社区成员
发帖
与我相关
我的任务
分享
public class Foo {
private int x = 100;
public int getX() {
return x;
}
public int fix(int y) {
synchronized (this) {
x = x - y;
}
return x;
}
public class MyRunable implements Runnable {
/**
* @param args
*/
private Foo foo = new Foo();
public static void main(String[] args) throws InterruptedException {
MyRunable r = new MyRunable();
new Thread(r, "Thread-A").start();
new Thread(r, "Thread-B").start();
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
this.fix(30);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ " 当前foo对象的值为:" + foo.getX());
}
}
public int fix(int y) {
return foo.fix(y);
}
public int fix(int y) {
synchronized (this) {
x = x - y;
System.out.println(Thread.currentThread().getName() + " 当前foo对象的值为:" + getX());
}
return x;
}
原因在于你的sleep(1000),当A去-30,然后睡1秒,在这一秒当中B-30,A醒了发现变成40了,然后A又-30,但是他还没执行完的时候,B醒了发现也是40.....