Java的同步与锁的问题
请大神们帮帮小弟这个synchronized问题吧~都纠结好久了,下面这是一个运算类的代码:
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;
}