क्या यह जावा में मॉनीटर करता है उदाहरण आवृत्ति चर तक पहुंच प्रतिबंधित नहीं करता है और सिंक्रनाइज़ किए गए कथन में सिंक्रनाइज़ या कोड घोषित किए जाने वाले तरीकों के लिए?क्या जावा मॉनिटर में इंस्टेंस चर शामिल हैं?
मैंने दो धागे बनाए हैं, thread y
सिंक विधि का आह्वान करता है, जिसे thread r
सिंक्रनाइज़ किया गया है, जबकि unsync विधि को आमंत्रित करता है जिसे सिंक्रनाइज़ नहीं किया जाता है। दोनों साझा ऑब्जेक्ट s
पर विधियों का आह्वान करते हैं।
Thread r
ऑब्जेक्ट s
के आवृत्ति चर को संशोधित करने में सक्षम है, जबकि उस ऑब्जेक्ट का मॉनीटर या लॉक अभी भी thread y
द्वारा आयोजित किया जा रहा है।
क्या यह है कि जावा में मॉनीटर आवृत्ति चर तक पहुंच प्रतिबंधित नहीं करता है, और सिंक्रनाइज़ किए गए कथन में सिंक्रनाइज़ या कोड घोषित किए जाने वाले तरीकों के लिए?
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