javaのモニターはインスタンス変数へのアクセスを制限していないのですか?synchronizedステートメントで宣言されたメソッドまたはsynchronizedステートメントのコードにのみアクセスできますか?javaモニタにインスタンス変数が含まれていますか?
私はthread y
がthread r
が同期宣言されていないUNSYNCメソッドを呼び出している間同期宣言された同期メソッドを呼び出し、二つのスレッドを作成しました。どちらも共有オブジェクトs
のメソッドを呼び出します。
Thread r
は、オブジェクトs
のインスタンス変数を、そのオブジェクトのモニタまたはロックがまだthread y
によって保持されている間に変更することができます。
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 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