java monitor是否包含实例变量?

Pus*_*raj 19 java synchronized

是java中的监视器不限制对实例变量的访问,而只限制对同步语句中声明为synchronized的方法或代码的访问?

我创建了两个线程,thread y调用sync方法,该方法在sync()调用未声明同步的unsync方法时声明为synchronized.两者都在共享对象上调用方法thread r.

unsync()能够修改对象的实例变量,s同时该对象的监视器或锁仍然被持有Thread r.

是Java中的监视器不限制对实例变量的访问,并且只限制声明为synchronized的方法或同步语句中的代码?

public class Stuff {

    private int a = 10;

    public synchronized void sync() {
        long t1 = System.currentTimeMillis();
        System.out.println("Okay, I am in sync() method. "
                        + "I will be waiting for 10 seconds. Current Time = "
                        + System.currentTimeMillis());
        while (System.currentTimeMillis() - t1 < 10000);
        System.out.println("Okay, I have waited for 10 seconds. Current time is "
                        + System.currentTimeMillis()
                        + ". Now I will exit from sync() method, a = " + this.a);
    }

    public void unsync() {
        System.out.println("Alright, I am in unsync() method. The current time is "
                        + System.currentTimeMillis());
        this.a = this.a + 1;
        System.out.println(". The time of exit from unsync() method is "
                        + System.currentTimeMillis());

    }
}

class T1 extends Thread {

    Stuff s;

    public T1(Stuff s) {
        this.s = s;
    }

    public void run() {
        s.sync();
    }
}

class T2 extends Thread {

    Stuff s;

    public T2(Stuff s) {
        this.s = s;
    }

    public void run() {
        s.unsync();
    }
}

class Main {

    public static void main(String args[]) throws Exception {
        Stuff s = new Stuff();
        T1 y = new T1(s);
        T2 r = new T2(s);
        y.start();
        Thread.sleep(2000);
        r.start();
    }
}
Run Code Online (Sandbox Code Playgroud)

该计划的输出如下:

 
Okay, I am in sync() method. I will be waiting for 10 seconds. Current Time = 1358801766310  
Alright, I am in unsync() method. The current time is 1358801768343. The time of exit from unsync() method is 1358801768343  
Okay, I have waited for 10 seconds. Current time is 1358801776310. Now I will exit from sync() method, a = 11

JB *_*zet 17

是.保持对象的监视器可防止另一个线程执行另一个代码块或在同一对象上同步.如果方法未同步,则任何线程都可以随时调用它,无论另一个线程是否持有监视器.

如果至少有一个线程修改此共享状态,则必须同步对共享声明,甚至只读访问的每次访问.