Java中的监视器是否不限制对实例变量的访问,而仅限于声明为同步的方法或同步语句中的代码?
我创建了两个线程,thread y
调用sync()
方法,该方法声明为同步,而thread r
调用unsync()
未声明为同步的方法。两者都调用共享对象上的方法s
。
Thread r
能够修改对象的实例变量,s
而该对象的监视器或锁仍由thread y
.
是不是 Java 中的监视器不限制对实例变量的访问,而仅限于声明为同步的方法或同步语句中的代码?
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();
}
}
程序的输出如下:
好的,我在 sync() 方法中。我将等待 10 秒。当前时间 = 1358801766310 好吧,我在 unsync() 方法中。当前时间为1358801768343。退出unsync()方法的时间为1358801768343 好的,我已经等了 10 秒。当前时间是 1358801776310。现在我将退出 sync() 方法,a = 11