java中的監視器是不是限制對實例變量的訪問,並且只限於在同步語句中聲明同步或代碼的方法?java監視器是否包含實例變量?
我創建了兩個線程,thread y
調用同步方法,它聲明同步,而thread r
調用未聲明同步的異步方法。都調用共享對象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 currrent 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 m {
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();
}
}
的程序的輸出是下面:
Okay, I am in sync method. I will be waiting for 10 seconds. Current Time = 1358801766310 Alright, I am in unsync method the currrent 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