日期:2014-05-20 浏览次数:20863 次
public class MyRunnable implements Runnable {
    private int x = 100;
    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            synchronized (this) {
                this.fix(30);
                try {
                    Thread.sleep(1);
                } catch (final InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + ":当前对象foo的x值=" + x);
        }
    }
    public static void main(final String[] args) {
        final MyRunnable r = new MyRunnable();
        final Thread ta = new Thread(r, "Thread-A");
        final Thread tb = new Thread(r, "Thread-B");
        ta.start();
        tb.start();
    }
    public int fix(final int y) {
        x = x - y;
        return x;
    }
}synchronized (this) {
                this.fix(30);
                try {
                    Thread.sleep(1);
                } catch (final InterruptedException e) {
                    e.printStackTrace();
                }
            }
Thread-A:当前对象foo的x值=40
Thread-B:当前对象foo的x值=40
Thread-B:当前对象foo的x值=10
Thread-B:当前对象foo的x值=-50
Thread-A:当前对象foo的x值=-50
Thread-A:当前对象foo的x值=-80