Javaのモニターはインスタンス変数へのアクセスを制限せず、同期宣言されたメソッドまたは同期ステートメントのコードのみにアクセスを制限しますか?
私は2つのスレッドを作成しました.invokesメソッドは同期宣言されていますが、invokesメソッドは同期宣言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